abnormal
1 Classification of anomalies
▪ In the Java language, abnormal conditions occurring during program execution are called "exceptions". Errors occur during Java compilation or running or running (for example, if the user is required to enter a number, but the user enters a string, an exception will occur)
The root interface of the Exception is Throwable, which has two sub interfaces, Error and Exception.
▪ Error: refers to the JVM error. At this time, the program is not executed and cannot be processed;
▪ Exception: refers to the exception generated during program operation, which can be handled by the user in the processing format.
Runtime exception
▪ An exception that the compiler does not require forced handling. It generally refers to the logic error in programming, which is an exception that programmers should actively avoid. java.lang.RuntimeException class and its subclasses are runtime exceptions.
▪ This kind of exception can not be handled because it is very common. If it is fully handled, it may affect the readability and running efficiency of the program.
Compile time exception
▪ An exception that the compiler requires to be handled. That is, the general exception caused by external factors when the program is running. The compiler requires that Java programs must catch or declare all compile time exceptions.
▪ For this kind of exception, if the program does not handle it, it may bring unexpected results.
2 exception handling
Mode 1:
try...catch, try...catch...finally, try...finally
try{ ...... //Code that may cause exceptions } catch( ExceptionName1 e ){ ...... //Handling measures when an exception of type ExceptionName1 is generated } catch( ExceptionName2 e ){ ...... //Handling measures when an exception of type ExceptionName2 is generated }[ finally{ ...... //A statement that is executed unconditionally regardless of whether an exception occurs } ]
▪ catch cannot exist independently of try
▪ Adding a finally block after try/catch is not mandatory
▪ catch can't be empty
▪ If there may be multiple exceptions in the program, multiple catches are needed to catch them, which have no order
▪ Execute the corresponding catch when an exception is caught, and finally when no exception is caught
Mode 2:
throws
▪ If a method (when the statement in is executed) may generate some kind of exception, but it is not sure how to handle this exception, the method should explicitly declare to throw an exception, indicating that the method will not handle these exceptions, but the caller of the method is responsible for handling them.
▪ In the method declaration, the throw statement can be used to declare the list of exceptions thrown. The exception type after throws can be the exception type generated in the method or its parent class.
▪ An overriding method cannot throw an exception type that is more extensive than the overridden method.
public class ReturnFinally { public static void main(String[] args) { // int i = test01(); // System.out.println(i); int i = test02(); System.out.println(i); } private static int test02() { int num = 10; try { System.out.println(num); return num; } catch (Exception e) { num += 10; System.out.println("exception occurred"); } finally { num++; System.out.println("Code that must be executed"); } return num; } public static int test01() { int num = 10; try { System.out.println(num); // In the function, if the return keyword is used before finally, execute finally before return, and then return return num + 1; } catch (Exception e) { System.out.println("exception occurred"); } finally { System.out.println("Code that must be executed"); } return num + 2; } } public class Error { public static void main(String[] args) throws RuntimeException{ try { MyException(5,-1); } catch (Exception e) { System.out.println(e.getMessage()); }finally {//Must execute System.out.println("Must execute"); } System.out.println("55"); } public static void MyException(int i,int j) {//throws RuntimeException{ int t; t = i/j; System.out.println("11"); if(i<0||j<0) { System.out.println("222"); throw new RuntimeException ("The number must be positive");//message } System.out.println("33"); System.out.println(t); System.out.println("44"); } }
3. Throw an exception manually
The keyword used to throw an exception manually is throw
▪ First, the exception class object is generated, and then the throw operation is implemented through the throw statement (submitted to the Java Server)
Line environment).
▪ The exception that can be thrown must be an instance of Throwable or its subclass.
public static void getDrink(int drinkType) throws DrinkNotFoundException { //Declaration exception if ( drinkType<1||drinkType>3){ throw new DrinkNotFoundException("Please enter the correct number"); } switch (drinkType) { case 1: System.out.println("Coffee"); break; case 2: System.out.println("Beer"); break; case 3: System.out.println("milk"); break; default: break; } }
4 user defined exception class
Generally, user-defined exception classes are subclasses of RuntimeException.
The user's own exception class must inherit the existing exception class. Exception is inherited here.
public class DrinkNotFoundException extends Exception { /** * */ private static final long serialVersionUID = 1L; public DrinkNotFoundException() { super(); // TODO Auto-generated constructor stub } public DrinkNotFoundException(String string) { super(string); // TODO Auto-generated constructor stub } }
This exception class is the custom exception class that manually throws exceptions above
The following is the test class
private static Scanner sc; public static void main(String[] args) { Coffee c = new Coffee(); Milk m = new Milk(); Beer b = new Beer(); sc = new Scanner(System.in); System.out.println("Please enter the number of the beverage you want to buy:"); try { int i = sc.nextInt(); Drink.getDrink(i); if(i==1){ c.taste(); }else if(i==2){ b.taste(); }else if(i==3){ m.taste(); } } catch (Exception e) { System.out.println(e.getMessage()); } }
When the number entered by the user is not 1-3, an exception will be generated. Manually throw it to the user-defined exception class and output the message edited by yourself.
public class yic { public static void main(String[] args) throws Class12.MyException { MyException(5,0); } public static void MyException(int i,int j) throws Class12.MyException { try { int t; t = i/j; System.out.println(t); } catch (ArithmeticException e) { // TODO Auto-generated catch block throw new MyException("Cannot be 0"); } } } public class MyException extends Exception { /** * */ private static final long serialVersionUID = 1L; public MyException(String string) { // TODO Auto-generated constructor stub super(string); } }
Don't mistakenly think that the red font is an error in your code. You should carefully analyze the error information. For example, the error information is customized here.
5 when return meets finally
We said before that the statement in finally must be executed, and the statement directly ends the function when it is executed to return.
public class ReturnFinally { public static void main(String[] args) { int i = test01(); System.out.println(i); } public static int test01() { int num = 10; try { System.out.println(num); // In the function, if the return keyword is used before finally, execute finally before return, and then return return num + 1; } catch (Exception e) { System.out.println("exception occurred"); } finally { System.out.println("Code that must be executed"); } return num + 2; } }
At this time, num+1 is executed, but num+2 is not executed,
In the function, if the return keyword is used before finally, execute finally and return before return is completed. It can be considered that return has got the data he wants at this time, but only made a concession to finally and let it execute first.
public static int test01() { int num = 10; try { System.out.println(num); // In the function, if the return keyword is used before finally, execute finally before return, and then return return num + 1; } catch (Exception e) { System.out.println("exception occurred"); } finally { System.out.println("Code that must be executed"); return num + 2; } }
If you put return in finally, the result is
It is generally not recommended to put this kind of code in finally. Finally, you need to put some important code to avoid delaying the operation of these codes due to errors.