1. What is exception handling?
Before we know what exception handling is, we might as well know what exception is. The so-called abnormality is abnormal and exceptional. Every software program will produce exceptions in the early stage of being written. Like any language, it will produce errors, and Java is no exception.
As we usually do: 1. Divisor is zero, 2. Array is out of bounds, which are all exceptions.
When the program we write may have exceptions, we need to capture and handle exceptions. This process is called exception handling.
2. What are the errors in Java?
Generally speaking, errors are divided into compilation errors and processing errors.
(1) . compilation error
Compilation error means that we may not know much about the syntax of the Java language when we write code everyday. For example, the syntax of Java requires that the end of each statement be marked with; end. Or the spelling of reserved words is incorrect, or the case is not distinguished, English; Written in Chinese;, And so on will cause compilation errors.
(2) . operation error
Running error: Generally speaking, the program is grammatically correct, and the program can be compiled and run, but the running result is different from what is expected. This situation may be caused by the programmer's thoughtless algorithm. For example, dead loop is a typical running error. Try to avoid dead loop when writing programs to avoid unnecessary troubles such as system crash.
3. Inheritance structure diagram of exceptions and errors
In Java, all exceptions and errors are inherited from the Throwable class. The inherited structure diagram is as follows:
Throwable has two subclasses: Error and Exception.
(1) . Error class
Error class inherits from Throwable class and generally refers to problems related to virtual machine, such as system crash, virtual machine error, insufficient memory space, method call stack overflow, etc. Such errors are generally thrown by the JVM. This kind of error cannot be recovered and prevented only by the program itself. In case of such error, we should try our best to make the program exit safely.
The Error class contains many subclasses:
abnormal | Error corresponding to exception |
---|---|
VirtualMachineError | Virtual machine error |
IOError | Input / output error |
AssertionError | assertion failure |
... | ... |
(2) , Exception class
The Exception class also inherits from the Throwable class, which refers to the exceptions that Java programs should catch. Among them, Java Lang. RuntimeException is one of the special subclasses. The RuntimeException class represents hidden dangers in programming or exceptions generated by the JVM at runtime, such as divisor zero, array out of bounds, null pointer and so on.
The Exception class also contains many subclasses:
abnormal | Error corresponding to exception |
---|---|
RuntimeException | Runtime exception |
NullPointException | Null pointer exception |
IOException | Abnormal input and output |
SQLException | SQL exception |
ClassNotFoundException | Class exception not found |
TimeoutException | Timeout exception |
... | ... |
4. Custom user exception
Sometimes the exceptions defined by the system can not meet our needs, and most of the exceptions defined by the system are in English, which seems very laborious. At this point, we can define exceptions by ourselves and use them to meet our logical requirements.
There are generally the following steps to use custom exceptions: (1)inherit java.lang.Exception Class or Other existing system exception classes, or User defined classes to declare custom exceptions Regular class. (2)Declare the exception in a custom method The member properties and member methods required by the class, Make it meet our logical needs.
For example, when the user's age is less than 0, an error that the age cannot be less than zero is reported
class ExceptionOne extends Exception{//Declare an Exception class that inherits from Exception public ExceptionOne(String ErrorMsg){ super(ErrorMsg); } } class Person{ private int age; Person(int age){ this.age=age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class Main { public static void main(String[] args) { Person p1 =new Person(-10); if (p1.getAge()<0){ try { throw (new ExceptionOne("Age cannot be less than zero")); } catch (ExceptionOne exceptionOne) { exceptionOne.printStackTrace(); } } } }
ExceptionOne: Age cannot be less than zero at Main.main(Main.java:27)
5. How to throw and catch exceptions?
Throw and throws can be used to throw exceptions, and try Catch to catch exceptions.
(1) Throw a single exception
In the above example, we threw the ExceptionOne exception using throw, which is a method of manually throwing an exception. System defined exceptions are automatically thrown by the JVM.
For example, if we accidentally take 0 as the divisor, IDEA will not report an error, and Java. Java will be reported when running Lang. arithmeticexception: / by zero error.
public class Main { public static void main(String[] args) { int x=6,y=0; System.out.println(x/y); } }
Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:5)
When the throw clause is used to throw an exception to the exception handler, the throw function does not need to throw an exception to this function. If the upper function does not handle the exception, continue to throw it up until a method that can handle the exception is found.
The following program is wrong.
The solution is under the program section. You can try not to look at it first, and then find a solution by yourself.
class ExceptionOne extends Exception{ public ExceptionOne(String ErrorMsg){ super(ErrorMsg); } } class Person{ private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Person(int age) { this.age = age; } } public class Main { public static void main(String[] args){ func1(); } public static void func1() throws ExceptionOne { func2(); } public static void func2() throws ExceptionOne{ Person p1=new Person(-10); if (p1.getAge()<0){ throw new ExceptionOne("Age cannot be less than zero"); } } }
resolvent:
(1) . add throws ExceptionOne after the main method. The Exception class after throw can be the parent or indirect parent of this Exception class. Because the ExceptionOne class inherits the Exception class, you can also add throws Exception after the main method to handle exceptions.
(2) Wrap func1() in the main method with a try... catch statement, as shown below
public static void main(String[] args){ try { func1(); } catch (ExceptionOne exceptionOne) { exceptionOne.printStackTrace(); } }
(2) Throw multiple exceptions
When there are multiple exceptions in a function, you can use try... Catch to catch exceptions. For example, an exception occurs in a method_ one,Exception_two,Exception_three exceptions, and all three exceptions inherit Exception_super class. We can use multiple catches to catch exceptions separately_ one,Exception_two,Exception_three exceptions.
class Exception_one extends Exception{//First exception class Exception_one(String ErrorMsg){ super(ErrorMsg); } }class Exception_two extends Exception{//Second exception class Exception_two(String ErrorMsg){ super(ErrorMsg); } }class Exception_three extends Exception{//Third exception class Exception_three(String ErrorMsg){ super(ErrorMsg); } } public class Main { public static void main(String[] args) { func(); } public static void func(){ try{ //An exception may appear here_ one,Exception_two,Exception_three errors }catch (Exception_one e1){ e1.printStackTrace(); }catch (Exception_two e2){ e2.printStackTrace(); }catch (Exception_three e3){ e3.printStackTrace(); } } }
Similarly, similar to throw and throws, catch can also catch subclasses of this exception class. It is also possible to write the func() function above in this way
public static void func(){ try{ //An exception may appear here_ one,Exception_two,Exception_three errors }catch (Exception e1){ e1.printStackTrace(); } }
When an Exception that we don't know clearly appears in the func() method, we can use Exception to catch it without indicating the type of Exception. The system will automatically identify the Exception.
public class Main { public static void main(String[] args) { func(); } public static void func(){ try{ int x=7/0; }catch (Exception e1){ e1.printStackTrace(); } } }
We automatically recognize the exception that the divisor cannot be 0.
java.lang.ArithmeticException: / by zero
at Main.func(Main.java:8)
at Main.main(Main.java:4)
(3) The difference between throw and throws
Throw: the throw clause is generally used in try inside a method Catch and try catch... Finally (later), used to throw exceptions.
Throws: throws is usually written at the signature of the method, that is, after the method name, and is used to throw an exception to the method calling it.
(4) Use of try... catch... finally
The usage of finally is in my article< Fresh students will meet! (super advanced) the most frequently asked Knowledge in Java interview >It is mentioned in the article.
The statement block after finally will be executed anyway
Just look at the code
public class Main { public static void main(String[] args) { System.out.println(func()); } public static int func(){ try{ throw new Exception(); }catch (Exception e){ e.printStackTrace(); return 2; }finally { System.out.println("finally Executed"); return 3; } } }
The result is
java.lang.Exception at Main.func(Main.java:8) at Main.main(Main.java:4) finally Executed 3