7.1 Exceptions and Handling
An exception is an abnormal situation that occurs while a program is running. An exception does not always mean the program must crash; with proper handling, a program can show a message, record the problem, or continue with later logic.
Common Exceptions
Common exceptions include:
NumberFormatException: text cannot be converted to a number, such as converting"3.6"toint.ArithmeticException: an invalid arithmetic operation, such as integer division by zero.ArrayIndexOutOfBoundsException: array index out of range.NullPointerException: calling a field or method through anullreference.FileNotFoundException: opening a missing file.IllegalArgumentException: a method received an unreasonable argument.
if, it often should be. Exceptions are best for failures that may only become clear at runtime.try, catch, and finally
Put risky code in try, error handling in catch, and cleanup code in finally. The finally block runs whether an exception happens or not.
import java.util.Scanner;
public class DivisionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.print("Enter dividend: ");
int dividend = Integer.parseInt(input.nextLine());
System.out.print("Enter divisor: ");
int divisor = Integer.parseInt(input.nextLine());
int quotient = dividend / divisor;
System.out.printf("%d / %d = %d%n", dividend, divisor, quotient);
} catch (NumberFormatException error) {
System.out.println("Only integers are supported.");
} catch (ArithmeticException error) {
System.out.println("Divisor cannot be 0.");
} finally {
System.out.println("This calculation is finished.");
}
}
}One possible run:
Enter dividend: 21
Enter divisor: 4
21 / 4 = 5
This calculation is finished.Java does not have Python's try-else. Success-only work is usually placed after the risky lines inside try. The flow still stays clear: try attempts, catch handles failure, and finally cleans up.
Catch Specific Exceptions
Do not start by writing an overly broad catch (Exception error). If every exception is caught, real bugs may be swallowed and become harder to find.
try {
int score = Integer.parseInt(input.nextLine());
} catch (NumberFormatException error) {
System.out.println("Score must be an integer.");
}This code catches only NumberFormatException because the expected failure is "input cannot be converted to an integer."
throw
throw actively throws an exception. It is useful for saying "this input does not satisfy the method's requirements." The problem is detected in the right place, and caller code decides how to handle it.
import java.util.Scanner;
public class ScoreDemo {
static double normalizeScore(int score) {
if (score < 0 || score > 100) {
throw new IllegalArgumentException("Score must be between 0 and 100.");
}
return score / 100.0;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.print("Enter score: ");
int score = Integer.parseInt(input.nextLine());
double ratio = normalizeScore(score);
System.out.printf("Score ratio: %.2f%n", ratio);
} catch (NumberFormatException error) {
System.out.println("Invalid input: score must be an integer.");
} catch (IllegalArgumentException error) {
System.out.println("Invalid input: " + error.getMessage());
}
}
}One possible run:
Enter score: 120
Invalid input: Score must be between 0 and 100.Here, normalizeScore() does not print the user message. It only protects its own input rule. The outer caller decides how to explain the problem to the user.