java 异常处理

来源:互联网 发布:淘宝 运营 系统架构 编辑:程序博客网 时间:2024/06/10 07:00

可控异常:

异常 说明 IOException 当发生某种I/O异常时,抛出此异常 SQLException 提供关于数据库访问错误或其他错误信息的异常 ClassNotFoundException 类没有找到异常 NoSuchFieldException 类不包含指定名称的字段时产生的异常 NoSuchMethodException 类不包含指定名称的方法时产生的异常

运行时异常:

方法 说明 IndexOutOfBoundsException 指示某集合或数组的索引值超出范围时抛出该异常 NullPointerException 当应用程序试图在需要对象的地方使用null时,抛出异常 ArithmeticException 当出现异常的运算条件时,抛出的异常 IllegalArgumentException 抛出的异常表明向方法传递了一个不合法或不正确的参数 ClassCastException 当试图将对象强制转换为不是实例的子类时,抛出该异常

获取异常信息:

方法 说明 String getLocalizedMessage() 获得此Throwable本地化描述 String getMessage() 获得此Throwable的详细消息字符串 void printStackTrace() 将此Throwable及其栈踪迹输出至标准错误流 String toString() 获得此Throwable简短描述
    try {        } catch (IOException e) {            e.getLocalizedMessage();            e.getMessage();            e.printStackTrace();            e.toString();        }

异常处理:

try…catch

try {    需要正常处理的语句;} catch (Exception e) {    对异常进行处理的语句;}

try…catch…finally

try {    需要正常处理的语句;} catch (Exception e1) {    对异常进行处理的语句 1;} catch (Exception e2) {    对异常进行处理的语句 2;} finally {    一定会执行的语句}

try…finally 如关闭数据库连接,关闭IO流等。

try {    需要正常处理的语句;} finally {    一定会处理的语句;}

使用throws抛出异常:

throws 通常用于方法声明,当方法中可能存在异常,却不想在方法中对其处理时,可以在声明方法时同时使用throws声明抛出异常,然后在调用该方法的其他方法中处理抛出的异常。
多个异常之前用“,”分开。

数据类型 方法名(形式参数) throws 异常类1,异常类2,异常类3….异常类n {
方法体;
}

//抛出异常的方法public void showinfo () throws Exception {  FileInputStream in = new FileInputStream("F:/AB.txt");}//捕获处理异常的方法public void methodName(){    try {        showinfo();//调用抛出异常的方法;    } catch (Exception e) {        System.out.println(e.getMessage());    }}

使用throw语句抛出异常:

throw语句通常用在方法中,在程序中自行抛出异常:
throw new Exception(“异常描述”);

if (a < 10)     throw new Exception("a不可以小于10");

方法中抛出异常:

public class ThrowException {    public static void throwException() {        throw new UnsupportedOperationException("不支持的操作"); //抛出异常    }    public static void main(String[] args) {        new ThrowException.throwException(); //调用抛出异常的方法    }}

方法上抛出异常

public class ThrowsException {    public static void throwsException() throws ClassNotFoundException { //抛出异常        Class.forName("com.mysql.jdbc.Driver");    }    public static void main(String[] args) {        try {   //捕获异常            ThrowsException.throwsException();  //调用抛出异常的方法;        } catch (ClassNotFoundException e) {            e.printStackTrace();        }    }}

自定义异常类:

public class NewException extends Exception {    public NewException (String s){        super(s);        System.out.println("出现了新异常");        System.out.println();    }}
原创粉丝点击