自定义异常

了解手动抛出异常对象和自动抛出

  • throw new 异常类的对象
  • throws 异常类对象,

两者区别

  • throw 在方法中用
  • throws在声明时用

使用场景

多个方法并列,可以使用throw

自定义异常

  • 继承于现有的异常体系。通常继承于RuntimeException \ Exception
  • 通常提供几个重载的构造器
  • 提供一个全局常量,声明为:static final long serialVersionUID;

如果继承RuntimeException运行时异常,则方法中可以这样用,

class Student{
    int id;

    public void regist(int id){
        if (id > 0){
            this.id = id;
        }else{
            // 手动抛出异常类对象
//            throw new RuntimeException("错误");
            throw new BelowZeroException();
        }


    }
}

public class BelowZeroException extends RuntimeException{

}

如果继承的不是运行时异常,则方法也要throws,

   public void regist(int id) throws Exception{
        if (id > 0){
            this.id = id;
        }else{
            // 手动抛出异常类对象
//            throw new RuntimeException("错误");
            throw new BelowZeroException();
        }


    }

public class BelowZeroException extends Exception{

}

相关推荐

  1. 认识异常定义异常

    2024-07-18 08:34:02       23 阅读
  2. 定义异常

    2024-07-18 08:34:02       21 阅读
  3. Springboot定义全局异常处理

    2024-07-18 08:34:02       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-18 08:34:02       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-18 08:34:02       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-18 08:34:02       58 阅读
  4. Python语言-面向对象

    2024-07-18 08:34:02       69 阅读

热门阅读

  1. leetcode-46. 全排列

    2024-07-18 08:34:02       23 阅读
  2. 观察者模式-C#

    2024-07-18 08:34:02       26 阅读
  3. 掌握JVM调优:如何在Gradle中配置JVM参数?

    2024-07-18 08:34:02       20 阅读
  4. vue2.0中如何实现数据监听

    2024-07-18 08:34:02       21 阅读
  5. D365 Fraud Protection Loss Prevention产品介绍

    2024-07-18 08:34:02       22 阅读
  6. 物联网与通信技术

    2024-07-18 08:34:02       24 阅读
  7. Hadoop3:MR程序压测实验

    2024-07-18 08:34:02       21 阅读
  8. MyBatis-Plus的几种常见用法

    2024-07-18 08:34:02       15 阅读
  9. HTTP协议——请求头和请求体详情

    2024-07-18 08:34:02       24 阅读
  10. C++--accumulate介绍

    2024-07-18 08:34:02       20 阅读