Sike Java, Java exception mechanism

Summary

Program can be used to specify an exception error occurred. An exception is thrown, the use of throwstatements and provide an exception object to provide specific information about the error that occurred. The method has been thrown out of uncaught checked then it must contain a statement throws clause.

First, what is the Exception?

Exception see you must be very familiar with this, but very strange, usually brought on by the encounter exception is thrown throw to go. But when people ask you: What is Exception? Prevarication can not tell you, but could not come to a 1 or 2, it is a quasi I said it. If I say quasi, then read on, this article is in line with you, my girlfriend can understand. I believe you can understand. If you know much about, then do not continue to read.

Speaking of which there may be no impression of Exception, see: try {...}catch (Exception e){...}now is not know what, if you see here, then please read on.

What is Exception?
Many blog are given directly code, but I'd better give the definition, want to learn, you have to know why it occurs.

定义: Exception is a mechanism for handling exceptions, during the execution of the program, suddenly there is a problem, then the exception handling mechanism will come in handy.

try, catch, finallyDescription:
try: tryblock identification code block exception may occur;
catch: catchblock identifies a block of code known as exception handlers, which i open a particular type of exception handling;
finally: finallyblock of code will be executed anyway a block identifier, and often cleaning position after closing the file, and resource recovery code embodied in the try block.

try statement should contain at least one catch finally block or blocks, and may have a plurality of catch blocks.

try {
	//可能发生运行错误的代码;
}catch (异常类型1  异常类型对象的引用){
	//处理异常类型1的代码
}catch (异常类型2  异常类型对象的引用){
	//处理异常类型2的代码
}finally {
	//用于最后处理的代码,此处的代码,不管怎么样都会执行。
}

Two, Java abnormal category (you are not only aware of two kinds, in fact, there are three kinds)

Many say there are two kinds of abnormalities, in fact, there are three (I turned the official website of java).

Three kinds of Java exceptions 检查时异常are: 错误异常, 运行时异常, .

第一种:检查时异常
通常是编写好的程序,这些异常能是在人的预期之内的

For example: Suppose there is a program, a document processing. This requires the user to enter an address path of the file, then the file address to the corresponding I / O processing, take FileRedaer, if the path to it, the program will run normally. But the program can not guarantee that every time a user provides correct the Road King, if the file path error, then the file does not exist, it will report the FileNotFoundExceptionexception. At this time, the program can prompt the user must enter the correct path.

For example: Users enter the account password, the password error, you can prompt the user to input errors.

第二种:错误异常:
通常这类异常是由程序外部的特殊条件造成的,应用程序通常是无法预期的;
For example: user manipulate files also take for instance, the program requires the user to provide the address of a file. If the address is correct, but the error, and other factors not open due to a malfunction of the machine caused. Called error exception.

Error exception is not 捕获of. Error is made Error及其子类指示的那些异常.

第三种:运行时异常:
这类异常时是发生在程序内部的,通常是由编程错误造成的;
Example: API logic error or improper use.

Second, capture and handle exceptions

Subsequently the analyzed together try, catch, finallythree use the exception handling block.

(1)(try-catch)

Captures a single abnormal

try{
	//会发生异常的代码块
}catch(异常类型  异常变量名){
	//发生异常后,应该怎么做
}

Multiple capture block

try{
	//会发生异常的代码块
}catch(异常类型1  异常变量名1){
	//发生异常类型1后,应该怎么做
}catch(异常类型2  异常变量名2){
	//发生异常类型2后,应该怎么做
}catch(异常类型3  异常变量名3){
	//发生异常类型3后,应该怎么做
}

try: For monitoring abnormal (monitor when an exception occurs)
catch: used to capture handle exceptions (how abnormal processing)

Explanation
try后面Content within a pair of braces will be monitored, stored some code may be a problem, once triggered, it shows there is an exception to happen. catch代码块It deals with these exceptions, once unusual, what to do? In it operates.

Example 1: The most common example of a divisor

        System.out.println("开始执行");
        int a = 10;
        int b = 0;
        int c = 5;
        System.out.println(a/b);
        System.out.println(a+c);
        System.out.println("我又做其他的事情了");
        System.out.println("执行结束了");

We can see will be reported the following exception: while it will not execute down, stop the program directly.
Here Insert Picture Description
Catch the exception to save it

       System.out.println("开始执行");
        int a = 10;
        int b = 0;
        int c = 5;

        try {
            System.out.println(a/b);
        }catch (ArithmeticException A){
            System.out.println("出现异常了,错误消息:"+A.getMessage());
        }
        System.out.println("我又做其他的事情了");
        System.out.println(a+c);
        System.out.println("执行结束了");

Here Insert Picture Description
You can see by the above example, the first statement to be monitored in order to perform normally, when faced with a problem statement, and a match is found abnormal, and executes the catch block statements generally speaking we will pass an exception in the catch block object to perform abnormal method.

Methods Explanation
public String getMessage() For more information on the back of an abnormal occurrence. This message is initialized in the constructor of the class Throwable
public Throwable getCause() Returns an object that represents the reason for the exception Throwable
public String toString() Use getMessage () returns the result of the class name of Cascade
public void printStackTrace() Print toString () result and stack level to System.err, ie the error output stream

(2)(try-catch-finally)

try-catchAnd then on the basis of a complementary finallyknowledge of
finallythe contents of the code block regardless of tay-catchhow the code two blocks of code, finallycontent block of code will execute.

The syntax is as follows:

try{
    ......
}catch(异常类型1 异常的变量名1){
    ......
}catch(异常类型2 异常的变量名2){
    ......
}finally{
    ......
}

Whether or not an exception occurs, fianlly always will always run

Note: When finally encountered return

E.g:

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

    public static String test(){
        int[] array = new int[2];
        try{
            array[3] = 0;
            return "This is try";
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
            return "This is catch 1";
        }catch (Exception e){
            System.out.println(e);
            return "This is catch 2";
        }finally {
            System.out.println("This is finally");
            //return "This is finally's return";
        }
    }
}

//运行结果
java.lang.ArrayIndexOutOfBoundsException: 3
This is finally
This is catch 1

This leads us to a conclusion:在catch中遇到return时,仍然会先执行finally语句

(3)throw/throws

Will not deal with their own, or in the method statement declares, tell the caller, there are problems.

 public static void main(String[] args) {
        int a = 10;
        int b = 0;
        System.out.println(aAndb(a, b));
    }

    public static int aAndb(int a,int b){
        if(b==0){
            throw new ArithmeticException();
        }else{
            return a/b;
        }
    }

Here Insert Picture Description

Upper handle exceptions

  public static void main(String[] args) {
        int a = 10;
        int b = 0;
        try {
            System.out.println(aAndb(a, b));
        }catch (ArithmeticException A){
            System.out.println("出错了,错误消息为:"+A.getMessage());
        }
    }

    public static int aAndb(int a,int b){
        if(b==0){
            throw new ArithmeticException("b不能为0");
        }else{
            return a/b;
        }
    }

Here Insert Picture Description

The difference (4) throws and throw the

1、throws

  • After the method declaration, with the class name is unusual
  • Can talk to multiple exception classes, separated by commas
  • Represents an exception is thrown, handled by the caller of the method
  • One possibility expressed throws an exception, not necessarily these exceptions occur

2、throw

  • Used in vivo, with the exception object name is
  • You can only throw an exception object name
  • It represents an exception is thrown, the statements in vivo treatment
  • Implementation of the throw must throw some abnormality

Third, a universal custom exception class

Java comes with exception class, basically to meet most of the problems we encountered, in addition, it can also be custom exception class.

Definition of a generic exception class

//通用异常类
class ZhenghuiException extends Exception {
    public ZhenghuiException(String msg)
    {
        super(msg);
    }
}

Test code

public class ListTest {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        try {
            System.out.println(aAndb(a, b));
        }catch (ZhenghuiException A){
            System.out.println("出错了,错误消息为:"+A.getMessage());
        }
    }

    public static int aAndb(int a,int b) throws ZhenghuiException {
        if(b==0){
            throw new ZhenghuiException("b不能为0");
        }else{
            return a/b;
        }
    }

}

Here Insert Picture Description

Published 154 original articles · won praise 617 · views 80000 +

Guess you like

Origin blog.csdn.net/qq_17623363/article/details/104908020