java异常--04--自定义异常类 和 全局异常处理机制

自定义异常类

在这里插入图片描述

如何自定义异常类?

  1. 继承于现有的异常结构;RuntimeException 、Exception
  2. 提供全局常量:serialVersionUID
  3. 提供重载的构造器

在这里插入图片描述

案例:

public class MyException extends Exception{
	
	static final long serialVersionUID = -7034897193246939L;
	
	public MyException(){
		
	}
	
	public MyException(String msg){
		super(msg);
	}
}

public class StudentTest {
	
	public static void main(String[] args) {
		try {
			Student s = new Student();
			s.regist(-1001);
			System.out.println(s);
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
	
}


class Student{
	
	private int id;
	
	public void regist(int id) throws Exception {
		if(id > 0){
			this.id = id;
		}else{

			throw new MyException("不能输入负数");
		}		
	}

	@Override
	public String toString() {
		return "Student [id=" + id + "]";
	}
	
	
}

在这里插入图片描述

全局异常处理机制

1 需求分析

说明: 通过try-catch 方式可以捕获异常.但是如果代码中有大量的数据需要通过try-catch的方式进行操作,会导致代码的结构混乱. 最好的方式可以采用全局异常处理的方式完成.
在这里插入图片描述

2 定义全局异常处理机制

package com.jt.aop;

import com.jt.vo.SysResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//spring中的通知 核心原理:Spring AOP机制
@RestControllerAdvice  //只对Controller代码层级有效.
public class SysResultException {

    //当程序发生异常时, 如果没有try-catch则直接向上抛出异常.
    //该注解只拦截运行时异常.
    @ExceptionHandler({RuntimeException.class})
    public SysResult exception(Exception e){
        e.printStackTrace();
        return SysResult.fail();
    }
}


注意;

@RestControllerAdvice 只对Controller代码层级有效.
@ExceptionHandler 该注解只拦截运行时异常
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值