throwable

throwable 异常体系笔记

throwable

  • throwable

    异常体系顶层接口

  • error

    throwable两大子接口之一 错误 (error),程序员 不处理

  • exception

  • throwable两大子接口之一 异常(exception),由程序员处理

  • runtimeException

    exception 下分支异常 运行时异常(runtimeException)

  • 常见异常
    NullPointerException
    IndexOutOfBoundsExecption
    FileNotFoundException

一、异常的常用方式

  1. try…catch{}finally
 //异常处理基本 方式
   	try{
   	//可能出现异常的代码...
  }catch(Excption e){
  // 出现符合指定异常时执行的代码....
  }finally{
   // 一定会被执行的代码(无论是否出现异常)
  //  一般用于资源释放
  }
  1. throw
    一定会出现异常的情况
    例如:
   //此处抛出必须是throwable 子类
   public class Test {
	  public static void main(String[] args){
       int i = 0;
       int j = 10;
       if(i == 0){
       // 此处执行,直接出现异常
           throw new Exception();
		}
        i / j  ;
   }
}

  • throws

    可能有问题 跟在方法名称后面

   public class Test {
     //若c硬盘中有a.txt 文件则不会出现异常,没有则会出现异常。throws 代表一种可能性
	  public static void main(String[] args) throws FileNotFoundException {
      File file = new File("c:\\a.txt");
      
   }

4.自定义异常使用

  • 自定义异常 必须是throwable 体系下类 一般是继承 Exception 与RuntimeException. 根据继承的接 口,异常检查的时期不同
  • 编写带参数构造方法,用于传递自定义错误信息
public class MyException extends Exception{

   public MyException (String message) {
       super(message);
   }

}

二、异常在Spring中的使用

  1. 创建自定义异常对象
/**
 * 自定义异常类格式
 */
 

/**
 * 自定义异常
 */
public class GlobalException extends RuntimeException implements Serializable {

    /**
     * 异常状态码
     */
    private String code;
    
    public GlobalException () {
    }
    public GlobalException (String code, String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

}
  1. 创建全局返回对象类
@ApiModel("返回数据")
@Data
@JsonSerialize()
public class Result<T> implements Serializable {
	/**
	 * 状态.
	 */
	@ApiModelProperty("返回状态(0表示成功)")
	private int code;

	/**
	 * 信息.
	 */
	@ApiModelProperty("返回信息")
	private String msg;

	/**
	 * 详细描述
	 */
	@ApiModelProperty("详细描述")
	private Object desc;

	/**
	 * 结果数据
	 */
	@ApiModelProperty("返回数据")
	private T data;

	/**
	 * 构造方法,默认OK
	 */
	public R() {
		this(0, "OK");
	}

	/**
	 * 构造方法
	 * @param code 状态
	 * @param msg 消息
	 */
	public R(int code, String msg) {
		this(code, msg,null);
	}

	/**
	 * 构造方法
	 * @param code 状态
	 * @param msg 消息
	 * @param data 数据
	 */
	public R(int code, String msg, T data) {
		super();
		this.code = code;
		this.msg = msg;
		this.data = data;
	}

}
  1. 创建全局异常处理类
    方式一: SpringMVC 添加ExceptionHandler 子类对象
       public class MyExceptionResolver implements org.springframework.
       web.servlet.HandlerExceptionResolver {

    /**
     * 异常处理方法
     *
     * @param request
     * @param response
     * @param handler   出现异常的对象
     * @param exception 出现的异常信息
     * @return ModelAndView
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, 
    HttpServletResponse response, Object handler, Exception exception) {
        log.error("系统统一异常处理:", exception);
        // 若响应已响应或已关闭,则不操作
        if (response.isCommitted()) {
            return new ModelAndView();
        }
       // 组装错误提示信息
        String errorCode = "404";
        String message = "操作异常";

        // 自定义业务相关异常 
      
       if (exception  instanceof GlobalException ) {
            errorCode = ((GlobalException )exception).getCode();
            message = exception.getMessage();
        }else if (exception instanceof Exception) {
            // 其它异常
            message = exception.getMessage();
            log.error(exception.getMessage());
        }

        // 响应类型设置
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        // 响应结果输出
        try (PrintWriter writer = response.getWriter()) {
            writer.write(ResultUtil.resultWithMessage(errorCode, message));
        } catch (Exception e) {
            log.error("响应输出失败!原因如下:", e);
        }
        return new ModelAndView();
    }
}


@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {

    /**
     * 400错误
     *
     * @param e
     * @return
     */
   @ExceptionHandler(GlobalException .class)
    public  handleRRException(GlobalException e) {
        log.error(e.getMessage());
        return new Result(1,e.getMessage());
    }

   
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值