[Java learning notes] exception handling

catalogue Category of exception Exception capture and thr...
Print out the call stack of the method  
Example 1:
Example 2:
be careful

catalogue

Category of exception

Exception capture and throw

Print out the call stack of the method  

Example 1:

Example 2:

be careful

Custom exception

Summarize the Java tutorial from teacher Liao Xuefeng:   Java Tutorial - Liao Xuefeng's official website (liaoxuefeng.com)https://www.liaoxuefeng.com/wiki/1252599548343744

Category of exception

Error indicates a serious error, and the program is generally unable to do anything about it, for example:

  • OutOfMemoryError: out of memory
  • NoClassDefFoundError: a Class could not be loaded
  • StackOverflowError: stack overflow

Exception is a runtime error, which can be captured and processed. It can be divided into two categories:

  • RuntimeException and its subclasses;
  • Non RuntimeException (including IOException, reflective operationexception, etc.)

Exceptions that do not need to be caught include Error and its subclasses, RuntimeException and its subclasses,

The compiler does not make mandatory capture requirements for RuntimeException and its subclasses, which does not mean that the application itself should not capture and process RuntimeException. Whether to capture and analyze specific problems

Exception capture and throw

Only one of multiple catch statements can be executed. For example:

public static void main(String[] args) { try { process1(); process2(); process3(); } catch (IOException e) { System.out.println(e); } catch (NumberFormatException e) { System.out.println(e); } }

When there are multiple catches, the order of catches is very important: subclasses must be written first. For example:

public static void main(String[] args) { try { ... ... } catch (IOException e) { System.out.println("IO error"); } catch (UnsupportedEncodingException e) { // Never catch System.out.println("Bad encoding"); } }

Unsupported encodingexception exception cannot be caught because it is a subclass of IOException. When an unsupported encoding exception is thrown, it will be caught and executed by catch (IOException e) {...}.

The correct way to write it is to put the subclass in front:

public static void main(String[] args) { try { ... ... } catch (UnsupportedEncodingException e) { System.out.println("Bad encoding"); } catch (IOException e) { System.out.println("IO error"); } }

Print out the call stack of the method  

The call stack of the method can be printed out through printStackTrace()  

Example 1:

public class Main { public static void main(String[] args) { try { process1(); } catch (Exception e) { e.printStackTrace(); } } static void process1() { process2(); } static void process2() { Integer.parseInt(null); // NumberFormatException will be thrown } }

From the bottom up,   Call hierarchy

main() 👉 process1() 👉 process2() 👉

👉 Integer.parseInt(String) 👉 Integer.parseInt(String, int)

You can see from the Integer.java source code that the method code for throwing an exception is as follows:

Example 2:

public class demo { public static void main(String[] args) { try { process1(); } catch (Exception e) { e.printStackTrace(); } } static void process1() { try { process2(); } catch (NullPointerException e) { throw new IllegalArgumentException(e); } } static void process2() { throw new NullPointerException(); } }

  It can be seen from Caused by: java.lang.NullPointerException that the root of the problem lies in the NullPointerException thrown by the Main.process2() method

be careful

  • To get the original exception in the code, you can use the Throwable.getCause() method. If null is returned, it indicates that it is already a "root exception"
  • When an exception is caught and thrown again, you must keep the original exception, otherwise it is difficult to locate the first crime scene
  • Throwing an exception in catch will not affect the execution of finally. The JVM will execute finally first and then throw an exception     (if an exception is thrown in finally,   The exception caught by catch will be lost,   It's like being transferred halfway,   This is called exception masking)

Custom exception

(quoted from) Custom exception - Liao Xuefeng's official website)

Maintain a reasonable exception inheritance system

A common approach is to customize a BaseException as a "root exception", and then derive exceptions of various business types.

BaseException needs to be derived from a suitable Exception. It is generally recommended to derive from RuntimeException:

public class BaseException extends RuntimeException { }

Exceptions of other business types can be derived from BaseException:

public class UserNotFoundException extends BaseException { } public class LoginFailedException extends BaseException { } ...

A custom BaseException should provide multiple construction methods:

public class BaseException extends RuntimeException { public BaseException() { super(); } public BaseException(String message, Throwable cause) { super(message, cause); } public BaseException(String message) { super(message); } public BaseException(Throwable cause) { super(cause); } }

In fact, the above construction methods copy the RuntimeException as it is. In this way, when throwing an exception, you can select the appropriate construction method. Through the IDE, you can quickly generate the construction method of the child class according to the parent class.

25 October 2021, 08:16 | Views: 8789

Add new comment

For adding a comment, please log in
or create account

0 comments