- package one;
- //自定义异常类
- class IsZeroException extends Exception {
- //自定义异常类的构造方法
- IsZeroException(String msg) {
- super(msg);
- }
- }
- public class Domo {
- public static void main(String[] args) {
- //捕获处理异常
- try {
- System.out.println(div(3, 0));
- } catch (IsZeroException e) {
- e.printStackTrace();
- }
- }
- //div方法使用异常类:通过 throws 声明异常
- public static double div(double a, double b) throws IsZeroException{
- //当b==0的时候抛出异常
- if(b == 0)
- throw new IsZeroException("除数为0");
- return a / b ;
- }
- }
复制代码 |
|