自学内容网 自学内容网

Spring-Boot中的异常处理方法

在运行程序时我们通常要进行异常的处理,一般有三种处理异常的方式

其中,常见的两种有try-catch,throws

一、异常处理方式1 —— throws

· throws:用在方法上,可以将方法内部出现的异常抛出去给本方法的调用者处理。

· 这种方式并不好,发生异常的方法自己不处理异常,如果异常最终抛出去给虚拟机将引起程序死亡。

抛出异常格式:

方法 throws 异常1 ,异常2 ,异常3 ..{
}
例:
public int divide(int dividend, int divisor) throws Exception{
return dividend/divisor;
}

代表可以抛出一切异常

二、异常处理方式2 —— try…catch

·这种也是非常常用的一种方式,可以更好的展示出程序的运行逻辑,适用于代理模式。

· 监视捕获异常,用在方法内部,可以将方法内部出现的异常直接捕获处理。

· 这种方式还可以,发生异常的方法自己独立完成异常的处理,程序可以继续往下执行。

格式:

/**
 * @author Mr.WBY
 * @version 1.0
 * @since 2024/7/18
 */
BufferedReader configReader = null;
try{
configReader = new BufferedReader(new FileReader(filePath));
String line;
StringBuffer content = new StringBuffer();
while ((line = configReader.readLine()) != null) {
content.append(line);
}
}catch (IOException e) {
e.printStackTrace();
}finally {
System.out.print("我爱吃大饼!")
}

Exception可以捕获处理一切异常类型!

三、使用Controller统一异常处理

·这是一种Spring-Boot特有的异常处理方式,由于在项目结构中,dao层和service层的代码最终都会执行到Controller层,所以异常也会,我们就可以在Controller层进行统一的异常处理。使用到的注解有:

@ControllerAdvice:统一为Controller进行"增强"

@ExceptionHandler : 异常处理

package com.ape.springboot01.util;


import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


/**
 * @author Mr.WBY
 * @version 1.0
 * @since 2024/7/18
 */
@ControllerAdvice
public class UtilException {

    @ResponseBody         //用来将我们
    @ExceptionHandler(BindException.class)             //直接用
    public String handlerBindException(BindException exception){
        return("全局异常处理");
    }
}

原文地址:https://blog.csdn.net/qq_64669006/article/details/140531043

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!