public class ExceptionTypeTest { public void doSomething()throws ArithmeticException{ System.out.println(); } public static void main(){ ExceptionTypeTest ett = new ExceptionTypeTest(); ett.doSomething(); } }
Question 1: Can the above program be compiled? And describe the reasons.
A: It can be compiled. Analysis: according to common sense, the dosomething method defines the arithmeticexception and calls this method in the main method. You should continue to throw or capture it. However, the arithmeticexception exception inherits the runtimeexception runtime exception. Java contains two types of exceptions: checked exception (check exception) and unchecked exception (unchecked exception
Check exceptions). For non-checked exceptions, it is also called runtimeexception (runtime exception). For runtime exceptions, the Java compiler does not require you to capture them or continue to throw them, however, for checked exception (check exception), you must capture or continue to throw it in the method.
Question 2: Can I compile the above program to change arithmeticexception to ioexception? And describe the reasons.
A: it cannot be compiled. Analysis: ioexception extends exception is a checked exception and must be captured or thrown.
Summary: Exceptions in Java are divided into two types: checked exception (check exception) and unchecked exception (not checked exception). For unchecked exceptions, it is also called runtimeexception (runtime exception ).
How to handle unchecked exceptions:
1. Capture
2. Continue to throw
3. Not handled
There are several ways to handle the checked exception (except runtimeexception:
1. Continue to throw. Negative methods can always be thrown to the Java Virtual Machine for processing.
2. Capture with try... catch
Note: The exception to be checked must be handled, captured, or thrown.