Home  >  Article  >  Java  >  Detailed explanation of JAVA exception class structure (with examples)

Detailed explanation of JAVA exception class structure (with examples)

王林
王林forward
2019-08-30 14:10:212679browse

1. The general structure of the exception class

Detailed explanation of JAVA exception class structure (with examples)

2.Throwable is the super class of all exception classes.

3. It should be used when an error (exception) may occur in the program, and use the key to catch the exception for processing.

4. The catch exception structure is as follows:

public void test() {
    int num1 = 10;
    int num2 = 0;
    try {
      System.out.println(num1 / num2);  // try可能出现错误的语句块
    } catch (Exception e) {    // 异常类型 并实例化一个异常类型e,用来对出现的异常进行说明
       e.printStackTrace();       // 如果出现错误执行catch里面内容,否则跳过catch语句块
    } finally {
        System.out.println("永远都会被执行,(system.exit)特殊情况除外,");// 无论是否出现异常都会执行finally语句块
    }
}

5. Some functions directly throw exceptions when they are declared and defined. When name is called, you need to catch the exception or continue to throw exceptions.

public static void main(String[] args) {
        try {
            test();             //调用这个方法就必须捕获异常或者继续抛出异常   
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    //方法定义的时候抛出了异常
    public static void test() throws Exception {
        int num1 = 10;
        int num2 = 0;
        System.out.println(num1 / num2);             
    }

6. Custom exception class must inherit an exception parent class:

public class ExceptionTest extends Exception{
    @Override        //这个是注解,表示这是重写的方法
    public void printStackTrace() {
        System.out.println("自己定义的异常类");
        System.out.println("尝试一下如果程序没有出现异常,强制抛出这个自定义异常,可不可以捕获");
    }   
}

7. Try to use (catch) a custom exception class

public class Main {
    public static void main(String[] args) {
        try {
            test();                    //调用这个方法尝试捕获自定义异常
        } catch (ExceptionTest e) {
            e.printStackTrace();    //自定义的异常类重写了printStackTrace这个方法
        }
    }
     //继续往上抛出异常
    public static void test() throws ExceptionTest{
        throw new ExceptionTest(); //强制产生一个自定义的异常并往上抛
    }   
}

If there are any mistakes, please criticize and point them out! For more related questions, please visit the PHP Chinese website: JAVA Video Tutorial

The above is the detailed content of Detailed explanation of JAVA exception class structure (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete