Java异常处理

简单处理

try {
    String a = "123a";
    int i = Integer.valueOf(a);
} catch (Exception e) {
   e.printStackTrace();
}

throws和throw关键字

throws表示当前方法不处理异常,而是交给方法的调用出去处理

throw表示直接抛出一个异常

package com.little;

public class Demo1 {
    static void demoThrows() throws Exception{
        String a = "123a";
        int i = Integer.valueOf(a);
    }
    public static void main(String[] args) {
        try {
            demoThrows();
        } catch (Exception e) {
           e.printStackTrace();
        }
    }
}

output

java.lang.NumberFormatException: For input string: "123a"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:580)

at java.lang.Integer.valueOf(Integer.java:766)

at com.little.Demo1.demoThrows(Demo1.java:6)

at com.little.Demo1.main(Demo1.java:10)

抛出异常示例:

package com.little;

public class Demo1 {
    static void demoThrow() throws Exception{
        throw new Exception("出错了.");
    }
    public static void main(String[] args) {
        try {
            demoThrow();
        } catch (Exception e) {
           e.printStackTrace();
        }
    }
}

java.lang.Exception: 出错了.

at com.little.Demo1.demoThrow(Demo1.java:5)

at com.little.Demo1.main(Demo1.java:9)

Exception和RuntimeException区别

Exception是检查型异常,在程序中必须使用try...catch进行处理

RuntimeException是非检查型异常,例如NumberFormatException,可以不使用try...catch进行处理,如果发生异常,则异常由JVM进行处理

RuntimeException最好也用try...catch捕获

自定义异常

public class CustomException extends Exception{
    public CustomException(String message) {
        super(message);
    }
}


public class Demo1 {

    private static void test() throws CustomException {
        throw new CustomException("自定义异常");
    }

    public static void main(String[] args) throws CustomException {
        test();
    }
}

Exception in thread "main" com.little.CustomException: 自定义异常

at com.little.Demo1.test(Demo1.java:6)

at com.little.Demo1.main(Demo1.java:10)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值