黑马程序员——Java 基础:异常

——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-

一、概述
  异常是 Java 程序在编译和运行过程中可能出现的错误和异常,Java 中将其封装成一个类,称之为 Throwable 类,即可抛出类,它有两个子类,分别为 Error(错误)类和 Exception(异常)类,Error 类中包含的通常是比较严重的问题,也是应用程序不应该出现的问题,在实际中需要获取异常信息并处理的通常是 Exception 类的异常,Exception 类有非常多的子类,包括 RuntimeException(运行时异常)等。
二、捕获并处理异常
Java 中用 try 和 catch 关键字来捕获和处理异常:

// 定义一个类,其中的方法是将两个整数的商返回
class Division {
    public int div (int a,int b) {
        int c = a/b;
        return c;
    }
}
// 在主方法中调用除法方法,但将除数设为零,用 try 和 catch 捕获并处理此异常
class Demo {
    public static void main (String[] args) {
        Division d = new Division();
        try {
            int c = d.div(4,0);
            System.out.println(c);
        }
        catch (Exception e) {
            System.out.println(e.toString());
        }
        System.out.println("over");
    }
}

  在上面代码的执行过程中,在执行 try 后面的代码块中的语句时,会在调用 div 方法时出现异常,然后该异常会被捕获并跳转到后面的 catch 方法对异常进行处理。
try catch 语句有三种格式,分别为:

try {
}
catch (Exception e) {
}

try {
}
catch (Exception e) {
}
finally {
}

try {
}
finally {
}

  其中 finally 后代码块中的语句在 try {} 中的语句没有执行 System.exit(0); 等退出虚拟机的语句时必定会执行,常用于关闭资源。

三、抛出异常
  如果一个函数在被调用时可能出现异常,可以在函数中通过 throw new Exception(); 语句抛出异常,如果在函数中存在抛出异常的语句,则需要在函数声明中添加 throws Exception:

class Demo {
    public static void main (String[] args) {
        try {
            int c = div(4,0);
            System.out.println(c);
        }
        catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    // 在方法中抛出异常
    public static int div (int a,int b) throws Exception {
        if (b==0)
            throw new Exception();
        return a/b;
    }
}

  在上面的代码中,函数 div 在函数中抛出了一个异常,因此方法声明后面要加上 throws Exception,意识是将异常交给调用函数的方法来处理,因此需要在调用函数时添加 try catch 语句捕获并处理异常,或是同样将异常抛出,交给 JVM 来处理。有一个特殊情况是,如果抛出的异常是 RuntimeException 可以不添加 throws Exception。

四、自定义异常
  可以自定义一个类,让其继承自 Exception 类,并在其构造方法中通过调用父类中构造方法来返回自定义信息。

// 自定义一个异常,并在其构造函数中调用父类方法
class MyException extends Exception {
    MyException (String message) {
        super(message);
    }
}

class Demo {
    public static void main (String[] args) {
        try {
            int c = div(4,0);
            System.out.println(c);
        }
        catch (Exception e) {
            System.out.println(e.toString());
        }
    }

    // 在方法中抛出自定义异常
    public static int div (int a,int b) throws Exception {
        if (b==0)
            throw new MyException("除数为零");
        return a/b;
    }
}

  在自定义异常的类的构造函数中通过 super(message); 调用的父类方法实际上是 Exception 类的父类 Throwable 类中的构造方法,该方法可以返回自定义的错误信息。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值