What is the exception
In an ideal state, the format of the data entered by the user is always correct, the selected open file must exist, and there will never be a Bug—— Java core technology
In order to avoid errors during program operation, Java uses an error capture mechanism called exception handling mechanism to handle exceptions.
The following are descriptions and supplements to the exception handling mechanism.
summary
The hierarchy of exceptions in Java (mainly) is shown in the following figure.
As can be seen from the above figure, Throwable is the class of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java virtual machine or can be thrown by the Java throw statement. Similarly, only this class or its subclasses can be parameter types in the catch clause.
Supplement:
Unchecked: unchecked exception.
Checked: exception checked.
When will exceptions be thrown?
If you encounter a situation that cannot be handled, the java method can throw an exception. So under what circumstances can exceptions be thrown?
1. User input error
2. Device error
3. Physical limitations
4. An error occurred in the program----- For example, a[-1]=0 will throw an uncheck ed exception of ArrayIndexOutOfBoundsException.
5. Call a method that throws the checked----- For example,. public FileInputStream(String name) throws FileNotFoundException
6. Errors found during program operation
7. Internal error in Java virtual machine and runtime library
Throw & catch exception?
This chapter mainly discusses the functions and differences of the keywords throw, throw, and try catch (finally).
[supplement] JVM's handling method for exceptions: print the tracking stack information of exceptions and terminate the program.
Throw exception
(1) Throws usually throws an exception after the declaration of the method header.
class MyAnimation{ public Image loadImage(String s) throws IOException{ ... } }
- Throws throws is a possible exception. (these exceptions do not necessarily occur)
- When the method is called, it must be caught, or it can throw an exception again, which is finally handled by the Java virtual machine.
- It is used to declare all exceptions that may be generated by a method (separated by), and upload the exceptions without any processing. I will throw them to whoever calls me.
The throw keyword is usually used in the method body and throws an exception object.
String readData(Scanner in)throws EOFException{ while(...){ if(!in.hasNext())//EOFException exception encountered if(n<len){ throw new EOFException(); }... } }
- Throw throws an exception. Executing throw must throw an exception.
- throw statements are handled by statements in the method body.
- Only one exception object can be thrown.
- There are two ways to capture. Either catch the exception try catch code block or throw an exception (throws exception).
Small summary
------It can be seen from the above comparison of throws and throw.
(1) When throw throws an exception object, the upper layer call of the function needs to handle the exception. At this time, it can be thrown through the try catch (finally) code block or throws. (be sure to handle it)
(2) throws can throw a possible exception without handling it.
Compile time exceptions need to be handled manually; The runtime exception jvm prints the trace stack information of the exception and terminates the program.
Therefore, generally, run-time exceptions do not need to be captured manually, but compile time exceptions need to be handled manually.
Try catch finally
- Exception capture is needed to write code.
- In java, even the code without exception can be caught with try catch.
[note] when defining a method, you can use the throws keyword to declare it. The method declared with throws means that the method does not handle exceptions, but is handed over to the caller of the method for processing.
[note] if throw is used and an exception is thrown, it must be caught and processed, that is, try catch or throws must be thrown.
Use 1:
try { //Exception code to be detected }catch(Exception e){ //Exception handling, that is, the code for handling exceptions (print exception information and handle it) }finally{ //Code that must be executed (usually to clear resources) }
Use 2:
try { //Exception code to be detected }catch(Exception e){ //Exception handling, that is, the code for handling exceptions (print exception information and handle it) }
Use 3:
try { //Exception code to be detected }finally{ //Code that must be executed (usually to clear resources) }
try { //Exception code to be detected }catch(Exception e1){ //Exception handling, that is, the code for handling exceptions (print exception information and handle it) }catch(IOException e2){ //Exception handling, that is, the code for handling exceptions (print exception information and handle it) }//Multiple exceptions can be handled through catch.
---------Take a chestnut-------
public class TestException { //Test 0 boolean testEx() throws Exception{ boolean res = true; try{ res = testEx1();//implement }catch (Exception e){ System.out.println("Test 0,Catch exception"); res = false; throw e; }finally{ System.out.println("Test 0, finally Final returned value =" + res); return res; } } //Test 1 boolean testEx1() throws Exception{ boolean res= true; try{ res = testEx2(); if (!res){ return false; } return res; }catch (Exception e){ System.out.println("Test 1, catch capture"); res = false; throw e; }finally{ System.out.println("Test 1, finally Final return value =" + res); return res; } } //Test 2 boolean testEx2() throws Exception{ boolean res = true; try{ int b = 2; int c; for (int i = 2; i >= 0; i--){ c = b / i; System.out.println("c="+c+"\ti=" + i); } return true; }catch (Exception e){ System.out.println("Test 2, catch capture"); res = false; throw e; }finally{ System.out.println("Test 2, finally Final value =" + res); return res; } } }//Learn from Angel_Kitty's example
Above results
How to throw an exception? (take a chestnut trumpet)
This section mainly describes the examples of the whole process of throwing exceptions and catching exceptions. Including custom exception classes.
Exception thrown by custom interface
public interface ComparePerson { // Compare whether two persons are equal void compareInfo(Person person1,Person person2) throws MyException; }
Custom exception class
//Custom Exception class (Exception class needs to inherit Exception) class MyException extends Exception{ public MyException(String s){//Output exception information System.out.println(s); } }
#3 define a class to implement this interface
public class Person implements ComparePerson { // full name private String name; // Age private int age; public Person(String name, int age) { this.name = name; this.age = age; } // If two persons are not equal, a user-defined exception will be thrown to print the information of two persons and the unequal information @Override public void compareInfo(Person person1, Person person2) { try{ System.out.println(person1.compare(person2)); }catch (MyException e){ // e.printStackTrace(); } } // Compare whether the two objects are the same, throw exceptions if they are different, and output exception information public String compare(Object obj) throws MyException {//The compareInfo method throws an exception in the interface. At this time, if you call the compare method, you also need to throw the desired exception. // Judge whether the addresses of the two objects are the same if (this == obj) { return "2 Personal attributes are exactly the same"; } // Judge whether obj object is a derived class (subclass) of Person if (obj instanceof Person) { System.out.println("********"); Person obj1 = (Person) obj;//The cast must be successful if (obj1.getName().equals(this.name) && obj1.getAge() == this.age) { throw new MyException("2 Personal attributes are the same!");//The upper level caller calling this method needs to throw this exception or use the try catch statement to catch the exception. } else if (obj1.getAge() == this.age) { //Print object details System.out.println(this.toString()); System.out.println(obj1.toString()); throw new MyException("2 Different personal names~"); } else if (obj1.getName().equals(this.name)) { //Print object details System.out.println(this.toString()); System.out.println(obj1.toString()); throw new MyException("2 Individual age is different~"); } } return "2 Individual difference a"; } //Print parameters public String toString() { return "name is:" + this.name + "\tage is:" + this.age; } //set get method public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Test main class loading test
class TestMain { public static void main(String[] args) throws MyException { // 2 Person objects Person person1 = new Person("Break it", 18); Person person2 = new Person("Han Han", 18); person1.compareInfo(person1, person2); } }
Above results
class TestMain { public static void main(String[] args) throws MyException { // 2 Person objects Person person1 = new Person("Break it", 18); Person person2 = new Person("Break it", 18); person1.compareInfo(person1, person2); } }
class TestMain { public static void main(String[] args) throws MyException { // 2 Person objects Person person1 = new Person("Break it", 18); Person person2 = new Person("Break it", 20); person1.compareInfo(person1, person2); } }
[note] in the above Person class, the e.printStackTrace() method is annotated. If the annotation is cancelled, the corresponding thrown exception information will be printed, as shown in the following figure:
The exception thrown above is user-defined exception information.
You can take the above example and run it directly. You can also learn more about this example!