Java Exception Handling 04. Sample program with exception handling

Опубликовано: 05 Октябрь 2024
на канале: Snipcademy
1,290
2

This video shows a simple implementation of exception handling.

The next video will show you how to use a more elegant syntax to handle exceptions - the try-with-resources feature.

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 u...  

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

/**
* Sample class that demonstrates exception handling
*
* @author CodeSnippetsAcademy
* @version 1.0.0
*/
public class Read10IntsWithHandling {
public static void main(String[] args) {

Scanner in = null;

// Let's try something...
try {

/** Unchecked exception - user may forget
to type file name */
String fileName = args[0];

/** Wrap anything that is related to IO
in a try-catch statement */
File inputFile = new File(fileName);
in = new Scanner(inputFile);

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

// Read in and output 10 integers
for (int i = 0; i less than SIZE; i++) {
arrayOfInts[i] = in.nextInt();
System.out.println(arrayOfInts[i]);
}

} catch (ArrayIndexOutOfBoundsException ex) {

System.err.println("Caught ArrayIndexOutOfBoundsException!");
System.err.println("Usage: java Read10IntsWithHandling 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.");

} finally {

if (in != null) {
System.out.println("\nAnd finally, closing scanner...");
in.close();
} else {
System.out.println("\nScanner was never opened.");
}

}

}
}