1. The abnormal

  • The basic concept of exceptions: Errors that occur during the running of a program are called exceptions

  • What exceptions do: Make your program more robust

  • All exceptions occur at run time.

  • Exceptions exist in Java in the form of classes, each of which can create exception objects.

2. Classification of exceptions

Why are exceptions classified?

What if Java had no division of exceptions into compile-time exceptions and run-time exceptions, and all exceptions had to be preprocessed at programming time? First of all, if so, the program must be absolutely safe. But programmers are too tired to write programs, and the code is littered with code that handles exceptions.Copy the code

2.1 Exception Hierarchy

2.2 Classification of exceptions

Exceptions are mainly divided into Error, compile-time Exception (Exception class), and RuntimeException (RuntimeException).

  • Error: If an Error occurs in the application, it cannot be recovered and the application can only be restarted. The most typical Error exception is OutOfMemoryError.

  • Compile-time exception: This exception occurs and must be handled; Java programs will not compile without handling it.

  • Runtime exceptions: This type of exception can be handled without explicit handling, such as dividing by 0, which Java does not require us to handle. (system.out.println(10/0))

3. Methods for handling exceptions

3.1 Throwing (reporting) exception classes using the keyword

  1. Throws “exception class” throws the exception to the method caller (JVM)
  2. Upselling is similar to passing the buck. (Continue passing the exception to the caller)
  3. Throws are generally not recommended on the main method. If an exception occurs, it must be thrown to the JVM, which will terminate the program

Note: Multiple classes can be written after throws, separated by commas (,)

    public class ExceptionTest05 {

        public static void main(String[] args) throws ClassNotFoundException {
            doSome();

        }

        public static void doSome() throws ClassNotFoundException{
            System.out.println("doSome!!!!");
        }
    }
    
Copy the code

3.2 use the try.. Catch Catches the exception class

To catch an exception is to block it and actually resolve it without the caller knowing

try.. Catch the grammar:

} catch (class name, variable name) {error after an exception}Copy the code

try.. Catch and throws are used together

public static void main(String[] args){ try { doSome(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void doSome() throws ClassNotFoundException{ System.out.println("doSome!!!!" ); }Copy the code

3.3 Attention to two exception handling methods

  1. As long as the exception is not caught and reported, the subsequent code of this method is not executed

  2. An exception occurs on a line in the try block, and the code after that line will not execute. Try… After the catch catches the exception, the rest of the code can be executed

3.3.1 How to choose between reporting and capturing

If you want the caller to handle selection reporting, otherwise use capture.

4. Further the try.. catch

4.1 catch statement

  1. The type inside catch() can be a specific exception type,

  2. Catch can write more than one. When advising catch, handle them precisely one by one. This is conducive to program debugging

  3. When a catch is written multiple times, the exception type must be followed from small to large, from top to bottom:

    FileInputStream fis = new FileInputStream("F:\\Java tutorial \\day08 work.txt "); // Read the file fis.read(); } catch (FileNotFoundException e) {system.out.println (" File does not exist!" ); } catch (IOException e) {system.out.println (" error! ); }Copy the code
  4. JDK8 new features: the catch () can be used in logic or tied for multiple exception class “|”, said that a class of several exception class occurs, perform to catch statement in the code

    FileInputStream fis = new FileInputStream("F:\\Java tutorial \\day08 work.txt "); System.out.println(100/0); / / this exception is a runtime exception, can handle also can not deal with} the catch (FileNotFoundException | ArithmeticException | a NumberFormatException e) {/ / JDK8 new features, To use logic or to indicate the existence of these exception classes, execute the following code: system.out.println (" File does not exist? Mathematical anomalies? Null pointer does not exist? Either way!" ); }Copy the code

4.2 the try.. The finally clause ina catch statement

  1. The code in the finally clause is executed last and must be executed even if an exception occurs in the try statement.

  2. The finally clause must occur with a try and cannot be written alone.

  3. Finally statements are usually used in:

  • Resource release/close is usually done ina finally block, because finally must be executedCopy the code

Example:

public class ExceptionTest10 { public static void main(String[] args) { FileInputStream fis = null; Fis = new FileInputStream("F:\\Java tutorial \\day08 work.txt "); fis = new FileInputStream("F:\\Java tutorial \\day08 work.txt "); String s = null; // null pointer exception s.tostring (); System.out.println("hello world"); Fis.close (); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); }finally {system.out.println (" Hello Hulk "); // If (fis! Fis.close () = null) {try {fis.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("hello kity"); }}Copy the code

4.3 Try Finally Is used together. Try cannot be used alone

public class ExceptionTest11 { public static void main(String[] args) try { System.out.println("try...." ); return; } finally { System.out.println(""); // Finally... }}}Copy the code

4.4 Finally statements do not execute until you exit the JVM

public class ExceptionTest12 { public static void main(String[] args) { try { System.exit(0); } finally {system.out. println("finally... ); }}}Copy the code

4.5 Finally

public class ExceptionTest13 { public static void main(String[] args) { int result = m(); System.out.println(result); Public static int m () {int I = 100; public static int m () {int I = 100; try { return i; } finally {i++;} finally {i++; Public static int m(){int I = 100; int j = i; i++; return j; } * /Copy the code

5. Exception objects have two important methods

  • Get an unusually simple description:

    String msg = exception.getMessage( );
    Copy the code
  • Print stack information for exception tracing (recommended) :

    exception.printStackTrace( );
    Copy the code
  • What about the anomaly tracking information?

    Line by line, look at your own code, SUN's code doesn't need to be looked atCopy the code

Method example:

public class ExceptionTest08 { public static void main(String[] args) { NullPointerException e = new NullPointerException(" NullPointerException "); // get the exception brief description. This is the String MSG = LLDB message (); System.out.println(msg); E.printstacktrace (); System.out.println("hello world"); }}Copy the code

6. Custom exceptions (emphasis)

  1. Reason for custom exception: The exception provided by SUN is not enough, need to custom exception class

  2. How to customize exception classes in Java:

    The first step is to write a class that inherits Exception or RuntimeException. The second step is to provide two constructors, one with no arguments and one with a String argumentCopy the code

Examples of custom exception classes:

7. Can’t throw more exceptions about method overrides

A rewritten method can throw no more (broader) exceptions than it did before it was written, only fewer

Class Animal{public void doSome(){} public void doOther() throws Exception {}} class Cat extends Animal /* Public void doSome() throws Exception {}*/ // The compiler is normal. /* Public void doOther(){}*/ / the compiler is normal. /* Public void doOther() throws Exception {}*/ / The compiler is normal /*public void doOther() throws NullPointerException {}*/}Copy the code

8. Wrap up

Exception catch: Try catch finally throws exception information to the caller manually.Copy the code