编程语言
首页 > 编程语言> > java什么时候需要定义异常类 异常类的使用场景

java什么时候需要定义异常类 异常类的使用场景

作者:互联网

每个类都有自已的名字,你自己Try-catch时要catch这个异常,才知道具体什么问题,进而做什么操作

假如登录时,有两个验证,账号错误,或密码错误,

你可以用系统的throw new Exception(“用户名错误”)

try{
   login(username,password);
}catch(Exception e){
      System.out.println(e.getMessage);
   doSomeThing.......
}

但是假如说其他问题呢 比如说数据库链接断了,你是不是应该重新登陆试试呢

都在这一个Exception 里,肯定满足不了要求的

try{
   login(username,password);
}catch(ErrorUserException e){
      System.out.println(e.getMessage);
   doSomeThing.......
}catch(SqlErrorException e){
        System.out.println(e.getMessage);
   doSomeThing.......
}

这样的话对应的异常会更加清晰

标签:Exception,场景,java,doSomeThing,System,getMessage,catch,异常,out
来源: https://blog.csdn.net/weixin_42362496/article/details/112028370