Home  >  Article  >  Java  >  Detailed explanation of JAVA exceptions and exception handling

Detailed explanation of JAVA exceptions and exception handling

尚
forward
2019-11-27 17:39:202143browse

Detailed explanation of JAVA exceptions and exception handling

1. Introduction to exceptions

What is an exception?

Abnormality is different from the normal situation, different from the normal situation, and there is an error. In Java, situations that block the current method or scope are called exceptions.

What is the exception system in Java? (Recommended: java video tutorial)

1. All abnormal classes in Java inherit from the Throwable class. Throwable mainly includes two major categories, one is the Error class and the other is the Exception class;

Detailed explanation of JAVA exceptions and exception handling

2. The Error class includes virtual machine errors and thread deadlocks. When an Error occurs, the program hangs completely and is called the program terminator;

Detailed explanation of JAVA exceptions and exception handling

3.Exception class, which is commonly referred to as "exception". Mainly refers to problems with coding, environment, and user operation input. Exceptions mainly include two categories, unchecked exceptions (RuntimeException) and checked exceptions (some other exceptions)

Detailed explanation of JAVA exceptions and exception handling

4 .RuntimeException exceptions mainly include the following four exceptions (in fact, there are many other exceptions, not listed here): null pointer exception, array subscript out-of-bounds exception, type conversion exception, and arithmetic exception. RuntimeException exceptions will be automatically thrown and automatically captured by the Java virtual machine (even if we do not write an exception capture statement, an error will be thrown during runtime!!). In most cases, such exceptions are caused by problems with the code itself and should be dealt with logically. Troubleshoot and improve the code.

Detailed explanation of JAVA exceptions and exception handling5. Check for exceptions. There are various reasons for this exception, such as the file does not exist, or there is a connection error, etc. Unlike its "brother" RuntimeException, for this exception we must manually add a capture statement to the code to handle the exception. This is also the main exception object we deal with when learning java exception statements.

Detailed explanation of JAVA exceptions and exception handling

2. try-catch-finally statement

(1) try block: responsible for catching exceptions , once an exception is found in try, control of the program will be handed over to the exception handler in the catch block.

[The try statement block cannot exist independently and must be co-stored with the catch or finally block]

(2) Catch block: How to deal with it? For example, issue warnings: prompts, check configuration, network connection, log errors, etc. After executing the catch block, the program jumps out of the catch block and continues to execute the following code.

[Notes on writing catch blocks: Exception classes handled by multiple catch blocks must be handled in a manner of catching the subclass first and then the parent class, because exceptions will be handled [nearby] (from top to bottom) . 】

(3) Finally: The code that is finally executed is used to close and release resources.

The syntax format is as follows:

try{
//一些会抛出的异常
}catch(Exception e){
//第一个catch
//处理该异常的代码块
}catch(Exception e){
//第二个catch,可以有多个catch
//处理该异常的代码块
}finally{
//最终要执行的代码
}

When an exception occurs, the program will terminate execution and be handed over to the exception handler (throwing reminders or recording logs, etc.), and the code outside the exception code block will execute normally. try will throw many types of exceptions, and multiple catch blocks will catch multiple errors.

Multiple exception handling code block order issues: first the child class and then the parent class (the compiler will prompt an error if the order is incorrect), and the finally statement block handles the code that will eventually be executed.

Next, let’s use examples to consolidate the try-catch statement~

Let’s look at the example first:

package com.hysum.test;

public class TryCatchTest {
    /**
     * divider:除数
     * result:结果
     * try-catch捕获while循环
     * 每次循环,divider减一,result=result+100/divider
     * 如果:捕获异常,打印输出“异常抛出了”,返回-1
     * 否则:返回result
     * @return
     */
    public int test1(){
        int divider=10;
        int result=100;
        try{
            while(divider>-1){
                divider--;
                result=result+100/divider;
            }
            return result;
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("异常抛出了!!");
            return -1;
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TryCatchTest t1=new TryCatchTest();
        System.out.println("test1方法执行完毕!result的值为:"+t1.test1());
    }
    
}

Running results:

Detailed explanation of JAVA exceptions and exception handling

Result analysis: The exception information thrown by the red words in the result is output by e.printStackTrace(), which shows that the exception type we throw here is an arithmetic exception, followed by the reason: by zero (Arithmetic exception caused by 0), the following two lines of at indicate the specific location of the code that caused this exception.

Add a test2() method to the above example to test the execution status of the finally statement:

/**
     * divider:除数
     * result:结果
     * try-catch捕获while循环
     * 每次循环,divider减一,result=result+100/divider
     * 如果:捕获异常,打印输出“异常抛出了”,返回result=999
     * 否则:返回result
     * finally:打印输出“这是finally,哈哈哈!!”同时打印输出result
     * @return
     */
    public int test2(){
        int divider=10;
        int result=100;
        try{
            while(divider>-1){
                divider--;
                result=result+100/divider;
            }
            return result;
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("异常抛出了!!");
            return result=999;
        }finally{
            System.out.println("这是finally,哈哈哈!!");
            System.out.println("result的值为:"+result);
        }        
    }         
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TryCatchTest t1=new TryCatchTest();
        //System.out.println("test1方法执行完毕!result的值为:"+t1.test1());
        t1.test2();
        System.out.println("test2方法执行完毕!");
    }

Running results:

Detailed explanation of JAVA exceptions and exception handling

Result analysis: We can see from the results that the finally statement block is executed last after the try block and catch block statements are executed. finally is executed after the expression behind return is calculated (at this time, the calculated value is not returned, but the value to be returned is saved first. No matter what the code in finally is, the returned value will not change. is still the previously saved value), so the function return value is determined before finally execution;

这里有个有趣的问题,如果把上述中的test2方法中的finally语句块中加上return,编译器就会提示警告:finally block does not complete normally 

public int test2(){
        int divider=10;
        int result=100;
        try{
            while(divider>-1){
                divider--;
                result=result+100/divider;
            }
            return result;
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("异常抛出了!!");
            return result=999;
        }finally{
            System.out.println("这是finally,哈哈哈!!");
            System.out.println("result的值为:"+result);
            return result;//编译器警告
        }
        
    }

Detailed explanation of JAVA exceptions and exception handling

分析问题: finally块中的return语句可能会覆盖try块、catch块中的return语句;如果finally块中包含了return语句,即使前面的catch块重新抛出了异常,则调用该方法的语句也不会获得catch块重新抛出的异常,而是会得到finally块的返回值,并且不会捕获异常。

解决问题:面对上述情况,其实更合理的做法是,既不在try block内部中使用return语句,也不在finally内部使用 return语句,而应该在 finally 语句之后使用return来表示函数的结束和返回。如:

Detailed explanation of JAVA exceptions and exception handling

 总结:

1、不管有木有出现异常或者try和catch中有返回值return,finally块中代码都会执行;

2、finally中最好不要包含return,否则程序会提前退出,返回会覆盖try或catch中保存的返回值。

3、  e.printStackTrace()可以输出异常信息。

4、  return值为-1为抛出异常的习惯写法。

5、  如果方法中try,catch,finally中没有返回语句,则会调用这三个语句块之外的return结果。

6、  finally 在try中的return之后 在返回主调函数之前执行。

三、throw和throws关键字

java中的异常抛出通常使用throw和throws关键字来实现。

throw ----将产生的异常抛出,是抛出异常的一个动作。

一般会用于程序出现某种逻辑时程序员主动抛出某种特定类型的异常。如:

语法:throw (异常对象),如:

public static void main(String[] args) { 
    String s = "abc"; 
    if(s.equals("abc")) { 
      throw new NumberFormatException(); 
    } else { 
      System.out.println(s); 
    } 
    //function(); 
}

运行结果:

Exception in thread "main" java.lang.NumberFormatException
at test.ExceptionTest.main(ExceptionTest.java:67)

throws----声明将要抛出何种类型的异常(声明)。

语法格式:

 public void 方法名(参数列表)
    throws 异常列表{
 //调用会抛出异常的方法或者:
 throw new Exception();
 }

当某个方法可能会抛出某种异常时用于throws 声明可能抛出的异常,然后交给上层调用它的方法程序处理。如:

public static void function() throws NumberFormatException{ 
    String s = "abc"; 
    System.out.println(Double.parseDouble(s)); 
  } 
    
  public static void main(String[] args) { 
    try { 
      function(); 
    } catch (NumberFormatException e) { 
      System.err.println("非数据类型不能转换。"); 
      //e.printStackTrace(); 
    } 
}

throw与throws的比较

1、throws出现在方法函数头;而throw出现在函数体。

2、throws表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某种异常对象。

3、两者都是消极处理异常的方式(这里的消极并不是说这种方式不好),只是抛出或者可能抛出异常,但是不会由函数去处理异常,真正的处理异常由函数的上层调用处理。

来看个例子:

throws e1,e2,e3只是告诉程序这个方法可能会抛出这些异常,方法的调用者可能要处理这些异常,而这些异常e1,e2,e3可能是该函数体产生的。

throw则是明确了这个地方要抛出这个异常。如:

void doA(int a) throws (Exception1,Exception2,Exception3){
      try{
         ......
 
      }catch(Exception1 e){
       throw e;
      }catch(Exception2 e){
       System.out.println("出错了!");
      }
      if(a!=b)
       throw new Exception3("自定义异常");
}

分析:

1、代码块中可能会产生3个异常,(Exception1,Exception2,Exception3)。

2、如果产生Exception1异常,则捕获之后再抛出,由该方法的调用者去处理。

3、如果产生Exception2异常,则该方法自己处理了(即System.out.println("出错了!");)。所以该方法就不会再向外抛出Exception2异常了,void doA() throws Exception1,Exception3 里面的Exception2也就不用写了。因为已经用try-catch语句捕获并处理了。

4、Exception3异常是该方法的某段逻辑出错,程序员自己做了处理,在该段逻辑错误的情况下抛出异常Exception3,则该方法的调用者也要处理此异常。这里用到了自定义异常,该异常下面会由解释。

使用throw和throws关键字需要注意以下几点:

1.throws的异常列表可以是抛出一条异常,也可以是抛出多条异常,每个类型的异常中间用逗号隔开

2.方法体中调用会抛出异常的方法或者是先抛出一个异常:用throw new Exception() throw写在方法体里,表示“抛出异常”这个动作。

3.如果某个方法调用了抛出异常的方法,那么必须添加try catch语句去尝试捕获这种异常, 或者添加声明,将异常抛出给更上一层的调用者进行处理

自定义异常

为什么要使用自定义异常,有什么好处?

1、我们在工作的时候,项目是分模块或者分功能开发的 ,基本不会你一个人开发一整个项目,使用自定义异常类就统一了对外异常展示的方式。

2、有时候我们遇到某些校验或者问题时,需要直接结束掉当前的请求,这时便可以通过抛出自定义异常来结束,如果你项目中使用了SpringMVC比较新的版本的话有控制器增强,可以通过@ControllerAdvice注解写一个控制器增强类来拦截自定义的异常并响应给前端相应的信息。

3、自定义异常可以在我们项目中某些特殊的业务逻辑时抛出异常,比如"中性".equals(sex),性别等于中性时我们要抛出异常,而Java是不会有这种异常的。系统中有些错误是符合Java语法的,但不符合我们项目的业务逻辑。

4、使用自定义异常继承相关的异常来抛出处理后的异常信息可以隐藏底层的异常,这样更安全,异常信息也更加的直观。自定义异常可以抛出我们自己想要抛出的信息,可以通过抛出的信息区分异常发生的位置,根据异常名我们就可以知道哪里有异常,根据异常提示信息进行程序修改。比如空指针异常NullPointException,我们可以抛出信息为“xxx为空”定位异常位置,而不用输出堆栈信息。

说完了为什么要使用自定义异常,有什么好处,我们再来看看自定义异常的毛病:

我们不可能期待JVM(Java虚拟机)自动抛出一个自定义异常,也不能够期待JVM会自动处理一个自定义异常。发现异常、抛出异常以及处理异常的工作必须靠编程人员在代码中利用异常处理机制自己完成。这样就相应的增加了一些开发成本和工作量,所以项目没必要的话,也不一定非得要用上自定义异常,要能够自己去权衡。

最后,我们来看看怎么使用自定义异常:

在 Java 中你可以自定义异常。编写自己的异常类时需要记住下面的几点。

所有异常都必须是 Throwable 的子类。

如果希望写一个检查性异常类,则需要继承 Exception 类。

如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。

可以像下面这样定义自己的异常类:

class MyException extends Exception{ }

我们来看一个实例:

package com.hysum.test;
public class MyException extends Exception {
     /**
     * 错误编码
     */
    private String errorCode;   
    public MyException(){}
    
    /**
     * 构造一个基本异常.
     *
     * @param message
     *        信息描述
     */
    public MyException(String message)
    {
        super(message);
    }
    public String getErrorCode() {
        return errorCode;
    }
    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }   
}

使用自定义异常抛出异常信息:

package com.hysum.test;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] sexs = {"男性","女性","中性"};
                  for(int i = 0; i < sexs.length; i++){
                      if("中性".equals(sexs[i])){
                          try {
                            throw new MyException("不存在中性的人!");
                        } catch (MyException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                     }else{
                         System.out.println(sexs[i]);
                     }
                } 
    }

}

运行结果:

Detailed explanation of JAVA exceptions and exception handling

四、java中的异常链

异常需要封装,但是仅仅封装还是不够的,还需要传递异常。

异常链是一种面向对象编程技术,指将捕获的异常包装进一个新的异常中并重新抛出的异常处理方式。原异常被保存为新异常的一个属性(比如cause)。这样做的意义是一个方法应该抛出定义在相同的抽象层次上的异常,但不会丢弃更低层次的信息。

我可以这样理解异常链:

把捕获的异常包装成新的异常,在新异常里添加原始的异常,并将新异常抛出,它们就像是链式反应一样,一个导致(cause)另一个。这样在最后的顶层抛出的异常信息就包括了最底层的异常信息。

》场景

比如我们的JEE项目一般都又三层:持久层、逻辑层、展现层,持久层负责与数据库交互,逻辑层负责业务逻辑的实现,展现层负责UI数据的处理。

有这样一个模块:用户第一次访问的时候,需要持久层从user.xml中读取数据,如果该文件不存在则提示用户创建之。

那问题就来了:如果我们直接把持久层的异常FileNotFoundException抛弃掉,逻辑层根本无从得知发生任何事情,也就不能为展现层提供一个友好的处理结果,最终倒霉的就是展现层:没有办法提供异常信息,只能告诉用户“出错了,我也不知道出了什么错了”—毫无友好性而言。

正确的做法是先封装,然后传递,过程如下:

1、把FileNotFoundException封装为MyException。

2、抛出到逻辑层,逻辑层根据异常代码(或者自定义的异常类型)确定后续处理逻辑,然后抛出到展现层。

3、展现层自行确定展现什么,如果管理员则可以展现低层级的异常,如果是普通用户则展示封装后的异常。

示例

package com.hysum.test;

public class Main {
    public void test1() throws RuntimeException{
        String[] sexs = {"男性","女性","中性"};
        for(int i = 0; i < sexs.length; i++){
            if("中性".equals(sexs[i])){
                try {
                    throw new MyException("不存在中性的人!");
                } catch (MyException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    RuntimeException rte=new RuntimeException(e);//包装成RuntimeException异常
                    //rte.initCause(e);
                    throw rte;//抛出包装后的新的异常
                }
           }else{
               System.out.println(sexs[i]);
           }
      } 
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Main m =new Main();
        
        try{
        m.test1();
        }catch (Exception e){
            e.printStackTrace();
            e.getCause();//获得原始异常
        }
        
    }

}

运行结果:

1Detailed explanation of JAVA exceptions and exception handling

Result analysis: We can see that the console first outputs the original exception, which is output by e.getCause(); then it outputs e.printStackTrace(), where you can see Caused by: the original exception and e The output of .getCause() is consistent. This forms an abnormal chain.

The function of initCause() is to wrap the original exception. When you want to know what exception occurred at the bottom layer, you can get the original exception by calling getCause().

Recommendations

Exceptions need to be encapsulated and passed. When we develop the system, we should not "swallow" exceptions, nor throw exceptions "naked". We should encapsulate and then throw them, or Through exception chain transmission, the system can be made more robust and friendly.

5. Conclusion

Java's exception handling knowledge is complicated and a bit difficult to understand. I have summarized it for you as follows. Some good coding habits when using Java exception handling:

1. When handling runtime exceptions, use logic to reasonably avoid and assist try-catch processing

2. In multiple catches After the block, you can add a catch (Exception) to handle exceptions that may be missed

3. For uncertain code, you can also add try-catch to handle potential exceptions

4. Try to handle exceptions as much as possible, remember to simply call printStackTrace() to print

5. How to handle exceptions specifically should be decided according to different business needs and exception types

6. Try to Add a finally statement block to release the occupied resources

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of Detailed explanation of JAVA exceptions and exception handling. 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