The exception handling mechanism in Java is designed to deal with exceptions that occur during program execution by predefining handling methods. When an exception occurs, the program processes it according to the predetermined methods. Java’s exception handling is implemented through five keywords: try, catch, finally, throw, and throws.
try-catch Keywords
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the dividend: ");
int a = input.nextInt();
System.out.print("Please enter the divisor: ");
int b = input.nextInt();
System.out.println("a/b=" + (a / b));
} catch (Exception e) {
System.err.println("Error occurred: both dividend and divisor must be integers, and divisor cannot be zero");
e.printStackTrace();
}
}
The try-catch statement first executes the statements in the try block. If the statements in the try block execute normally without any exceptions, the result of a/b will be directly output, and the catch block will not be executed.
If an exception occurs during the execution of the try block (such as division by zero), the output of a/b will be skipped, and the program will jump to the catch block to print the error that occurred.
try-catch-finally for Exception Handling
The try-catch-finally statement is a supplement to try-catch.
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the dividend: ");
int a = input.nextInt();
System.out.print("Please enter the divisor: ");
int b = input.nextInt();
System.out.println("a/b=" + (a / b));
} catch (Exception e) {
System.err.println("Error occurred: both dividend and divisor must be integers, and divisor cannot be zero");
e.printStackTrace();
} finally {
System.out.println("Thank you for using");
}
}
You just need to add a finally block after catch. The finally block will execute regardless of whether an exception occurs.
In the try-catch-finally structure, try must exist, while catch and finally blocks are optional, but at least one of them must appear.
throws Declaration to Throw Exceptions
If an exception is thrown in a method body and you want the caller to catch it in a timely manner, you can use throws to declare the various exceptions that a method might throw to notify the caller. throws can declare multiple exceptions at the same time, separated by commas.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test2 {
public static void divide() throws Exception {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the dividend: ");
int a = input.nextInt();
System.out.print("Please enter the divisor: ");
int b = input.nextInt();
System.out.println("a/b=" + (a / b));
}
public static void main(String[] args) {
try {
divide();
} catch (InputMismatchException e) {
System.err.println("Both dividend and divisor must be integers");
} catch (ArithmeticException e) {
System.err.println("Divisor cannot be zero");
} catch (Exception e) {
System.err.println("Other unknown errors");
} finally {
System.out.println("Thank you for using!");
}
}
}
Exceptions are caught through try-catch and declared through throws. If the caller doesn’t know how to handle the exception, they can continue to declare it using throws, leaving it to the upper-level caller to handle.
Using throw to Throw Exceptions
public class Person {
private String name = "A Wei";
private int age;
public void setAge(int age) throws Exception {
if (age >= 1 && age <= 100) {
this.age = age;
System.out.println(this.name + "'s age is: " + age);
} else {
throw new Exception("A Wei is already dead!");
}
}
public static void main(String[] args) {
Person p = new Person();
try {
p.setAge(500);
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
} finally {
System.out.println("You chose this, idol!");
}
}
}
In addition to exceptions automatically thrown by the system, during programming, there are some issues that the system cannot automatically identify, such as an age outside the normal range. In such cases, it’s necessary for programmers rather than the system to throw exceptions, passing the problem to the caller for handling. In the above example, we set the age to 500, which is obviously outside the normal range. However, if we don’t choose to throw it ourselves, the system itself cannot distinguish between right and wrong. Whether we input 500 or 50, the system will only recognize it as an integer, a correct number, so we need to throw this exception ourselves.
Differences between throw and throws
- Different roles: throw is used to generate and throw exceptions in the program, while throws is used to declare that exceptions are thrown within the method.
- Different positions: throw is located inside the method body and can be used as a separate statement; throws must follow the method parameter list and cannot be used alone.
- Different content: throw throws one exception object, only one; throws is followed by exception classes and can be followed by multiple.
Common Exception Classes
- Exception: The root class of the exception hierarchy
- ArithmeticException: Arithmetic error exception, such as division by zero
- ArrayIndexOutOfBoundsException: Array index out of bounds
- NullPointerException: Attempt to access a null object member
- ClassNotFoundException: Unable to load the required class
- InputMismatchException: Mismatch between the expected data type and the input
- IllegalArgumentException: Method received an illegal parameter
- ClassCastException: Error in object cast
- NumberFormatException: Number format conversion exception, such as converting “abc” to a number