Java Exception Handling 06. Making your own exception class

Опубликовано: 25 Апрель 2026
на канале: Snipcademy
2,231
5

This video will show you how to make your own exception class.

The following code may have been altered to comply with youtube's video description policy. To download the actual files, go here:
   • Java Exception Handling 00. Setting up and...  

import java.io.FileNotFoundException;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.File;

/**
Read in 10 integers, but make sure they're not negative

@author CodeSnippetsAcademy
@version 1.0.0
*/
public class Read10IntsNoNegatives {
public static void main(String[] args) {

final int SIZE = 10;
int[] arrayOfInts = new int[SIZE];

try (Scanner in = new Scanner(new File(args[0]))) {

// Read in and output 10 integers
for (int i = 0; i lessthan SIZE; i++) {
arrayOfInts[i] = in.nextInt();
if (arrayOfInts[i] lessthan 0) throw new NegativeValueException();
System.out.println(arrayOfInts[i]);
}

} catch (NegativeValueException ex) {

System.err.println("Caught NegativeValueException!");
System.err.println("Please make sure no negative values are in the input text file.");
} catch (ArrayIndexOutOfBoundsException ex) {

System.err.println("Caught ArrayIndexOutOfBoundsException!");
System.err.println("Usage: java Read10Ints fileName");

} catch (FileNotFoundException ex) {

System.err.println("Caught FileNotFoundException!");
System.err.println("File not found.");

} catch (InputMismatchException ex) {

System.err.println("Caught InputMismatchException!");
System.err.println("Please make sure input text file has integer values.");

}

}
}