3.1 Handling exceptions
Exception: an unexpected incident that stops the normal execution of the program
NOTE: scnr.nextInt accepts inputs that begin with + or - to indicate sign and accepts inputs that optionally use commas to separate every third digit
Try block: surrounds normal code; exits immediately if a statement throws an exception
Catch block (exception handler): catches an exception that matches the parameter type thrown in preceding try block
3.2 Throwing exceptions
NOTE: Java throws an ArithmeticException for in integer division by zero; floating-point division by zero results in NaN or infinity
throw: throws a throwable object during program execution
NOTE: list most specific (subclass) exceptions first, followed by general (superclass) exceptions becuase JVM evaluates catch blocks sequentially
3.3 Exceptions with methods
Throw clause: specifies the types of exceptions that a method may throw and callers should handle
Checked and unchecked exceptions
Checked exception: expect a programmer to handle within the program
Unchecked exception: Not expect a programmer to catch and handle at runtime
Java’s catch or specify requirements requires methods to either catch the checked exception or specify that methods throws the checked exception
NOTE: RuntimeException and Error and thier subclasses are the only unchecked exceptions in Java
3.4 User-defined exceptions
Define custom exception by extending an existing exception classes, with option to add custom constructors, methods, and variables
3.5 Exceptions with files
Closing files:
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
// need to catch checked exception: FileNotFoundException
import java.io.FileNotFoundException;
try {
// open input file
FileInputStream in = new FileInputStream("input.txt");
Scanner scnr = new Scanner(in);
// open output file
FileOutputStream out = new FileOutputStream("output.txt");
PrintWriter writer = new PrintWriter(out);
...
} catch (FileNotFoundException e) {
...
}
// close both files
scnr.close();
writer.close();Closing files with try-with-resources:
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintWriter;
// need to catch checked exception: FileNotFoundException
import java.io.FileNotFoundException;
try (
// open input file
FileInputStream in = new FileInputStream("input.txt");
Scanner scnr = new Scanner(in);
// open output file
FileOutputStream out = new FileOutputStream("output.txt");
PrintWriter writer = new PrintWriter(out);
) {
...
} catch (FileNotFoundException e) {
...
}
// automatically close both files after the try block exitsFinally block: always executes when a try block exits
NOTE: A try-with-resources variable must be newly declared, final, or effectively final