Java's exception system

1. abnormal system

  1. Almost all of the code will appear abnormal, in order to ensure that the program can normally finished after an exception occurs , to maximize the reduction of a means of protecting losses.
  2. Java exception is class.
  3. Exception class inheritance: Only Throwable and its subclasses abnormality can be captured and processed.

! [! [Insert Picture description here] (https://img-blog.csdnimg.cn/20190503141400683.png] (https://img-blog.csdnimg.cn/20190503141431172.png?x-oss-process= image / watermark, type_ZmFuZ3poZW5naGVpdGk, shadow_10, text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21pX3poaV9sdQ ==, size_16, color_FFFFFF, t_

  • Error: Description JVM runtime internal error, stack overflow, heap overflow;
  • Exception: program ubiquitous problem arises because the code;
    • IOException: generated due to the abnormal input and output, such as opening a file that does not exist in the program;
    • RuntimeException: occurs at runtime exception, not compile-time error. The array bounds exception, translation exception type, null pointer exception (NPE)
      checked exception : In addition to all the non-exception classes checked exception belong checked exception. I.e., to force the user to process.
      Non-checked exception : Error, RuntionException its subclasses. I.e., user is not forced to process.

2. Exception Handling

Exception Handling: When an exception is generated, try to ensure that the code may be performed after the abnormality.
Exception handling in three formats:

1. try...[1...N]catch...
2. try...finally...
3. try...[1...N]catch...finally...
  • try: all possible abnormal code appears;
  • catch: when the respective abnormality occurs, catches the exception and customize treatment;
  • finally: to ensure that the focus of the code (eg: IO streams closed, the release JDBC resources and connection is closed network) mechanism will be executed, regardless of whether or not an exception, finally content code will be executed.

Example: abnormal

public class ExceptionTest {
    public static void main(String[] args) {
        System.out.println("1.数学计算前...");
        System.out.println("2.数学计算中..."+(10/0));  //运行时异常
        System.out.println("3.数学计算后...");    //不能被执行
    }
}
/**
1.数学计算前...
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at www.csdn.qh.ExceptionTest.main(ExceptionTest.java:11)
*/

Example: Exception Handling
If an exception occurs, execution catch statement; If no exception, catch statement is not executed

public class ExceptionTest {
    public static void main(String[] args) {
        System.out.println("1.数学计算前...");
        try {
            System.out.println("2.数学计算中..."+(10/0));
        } catch (Exception e) {
            System.out.println("异常被处理了");      
        }
        System.out.println("3.数学计算后...");
    }
}
/**
1.数学计算前...
异常被处理了
3.数学计算后...
*/

Although the above code exception handling, but you do not know what the program generates an exception, so in order to obtain more information on exceptions, can be directly output exception class object, or call the exception class provided printStackTrace()a method and outputs complete exception information.
Example: abnormality information output

public class ExceptionTest {
    public static void main(String[] args) {
        System.out.println("1.数学计算前...");
        try {
            System.out.println("2.数学计算中..."+(10/0));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("3.数学计算后...");
    }
}
/**
1.数学计算前...
java.lang.ArithmeticException: / by zero
3.数学计算后...
*/

Example: Use try...catch...finally...exception handling 1
a finally unified export as a program.

public class ExceptionTest {
    public static void main(String[] args) {
        System.out.println("1.数学计算前...");
        try {
            System.out.println("2.数学计算中..."+(10/0));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println("不管是否有异常,都会执行此句");
        }
        System.out.println("3.数学计算后...");
    }
}
/**
1.数学计算前...
java.lang.ArithmeticException: / by zero
不管是否有异常,都会执行此句
	at www.csdn.qh.ExceptionTest.main(ExceptionTest.java:12)
3.数学计算后...
*/

Example: Use try...catch...finally...exception handling 2

public class ExceptionTest {
    public static void main(String[] args) {
        System.out.println(test());    //2
    }

    public static  int  test(){
        try {
            System.out.println(10/0);
            return 0;
        }catch (ArithmeticException e){
            return 1;
        }finally {
            return 2;
        }
    }
}

Regardless of whether there is an exception, finally the code will be executed and try the priority to try and catch code
Example: The JVM exit exit (), this will not execute finally

public class Test {
    public static void main(String[] args) {
        try {
            System.out.println("1");
            //系统退出
            exit(0);
        } catch (Exception e) {
            System.out.println("2");
        } finally {
            System.out.println("3");
        }
    }
}
//1

Abnormal (non-checked exception) 2.1 Non-operating

* Error, RuntimeException and its subclasses, * user is not forced to process.

public class Test {
    public static void main(String[] args) {
        System.out.println("1.计算开始");
        try{
            fun();
            System.out.println("2.计算开始");
        }catch (Throwable e){  //也可以替换成Error
            e.printStackTrace();   //java.lang.StackOverflowError
        }
        System.out.println("3.计算结束");
    }

    private static void fun() {
        fun();
    }
}

2.2 unchecked exception

In the IDE tool, draw red lines under the code, not compile, must deal with all your heart.

public class TestString {
    public static void main(String[] args) {
        File file = new File("abc.txt");
        try {
            InputStream inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {   //继承IOException
            e.printStackTrace();
        }
    }
}

3.throws

throws: the method used in the statement, made it clear that this method may be an exception. When an exception, an exception will be thrown at the caller, who is who transfer process.

public class Test {
    public static void main(String[] args) {

        try {
            System.out.println(caculate(10,0));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static int caculate(int a, int b)throws Exception {
        return a/b;
    }
}
//java.lang.ArithmeticException: / by zero

When an exception occurs, an exception will be thrown back method to the caller when the caller does not handle, you can continue to throw back . It is actually a handsome pot process
, for example: the main method throws an exception

public class Test {
    public static void main(String[] args) throws Exception{
        System.out.println(caculate(10,0));
    }

    private static int caculate(int a, int b)throws Exception {
        return a/b;
    }
}
//Exception in thread "main" java.lang.ArithmeticException: / by zero

4. throw

throw: used in a method for artificially represents an exception object. General and with the use of custom exception class.
Examples: Non checked exception throw of

public class Test {
    public static void main(String[] args) {
        test();  //运行时异常可以不处理
    }

    private static void test() {
        throw new RuntimeException("扔个异常");
    }
}

For example: throw a checked exception

public class TestString {
    public static void main(String[] args) throws Exception{
        test();  //运行时异常可以不处理
    }

    private static void test() throws Exception{
        throw new Exception("扔个异常");  //报红应处理,此处不处理扔出去
    }
}

Summary: The difference between Exception and RuntimeException

  1. Exception is RuntimeException using parent class, defined using the Exception exception requires exception handling must be used, and the use defined RuntimeException abnormal abnormality may optionally be handled by the user
  2. Common RuntimeException: classCastException, NullPointerException, etc.

The custom exception class

  • In Java, for procedural issues that may arise public will be provided with the appropriate information abnormalities, but these anomalies often enough for us to use. So we can define a class of their own exception
  • Custom exception class can inherit the parent class two kinds: Exception, RuntimeException
    for example: custom exception class
public class TestString {
    public static void main(String[] args) {
        int a = 1;
        int b = 1;
        int c = a+b;
        if(c == 2){
            throw new AddEexception("此时1+1不能等于2");
        }
    }
}

class AddEexception extends RuntimeException{
    public AddEexception(String msg){
        super(msg);
    }
}

Guess you like

Origin blog.csdn.net/mi_zhi_lu/article/details/89787965