异常处理

基本语法

Java异常类都实现了Throwable接口,分为两类异常,一类是编译时异常,另一类是RuntimeException,都继承了Exception类。
编译时的异常不需要用户自己处理,Java异常处理机制的应用对象都是运行时异常。
在程序中用throw关键字抛出异常,一旦抛出异常,要么通过try—catch处理异常,要么用throws关键字向上一级抛出异常。

interface A{
    void f() throws NullPointerException;
}

class B implements A{

    @Override
    public void f() throws NullPointerException {
        throw new NullPointerException();
    }

    public static void main(String[] args) {
        B b = new B();
        try{
            b.f();
        }
        catch (NullPointerException e){
            e.printStackTrace();
            System.out.println("accepted");
        }
        finally {
            System.out.println("Must handle");
        }
    }
}

java.lang.NullPointerException
	at exceptionHandling.B.f(TestStackTrace.java:24)
	at exceptionHandling.B.main(TestStackTrace.java:30)
accepted
Must handle

try语句块中可以抛出多个异常,编译器会自动匹配后面catch语句块中最合适的异常
finally关键字后的语句块无论抛不抛出异常都会执行,适合进行一些清理操作

其他操作

日志操作

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Logger;

class LoggingException extends Exception{
    LoggingException(){}
    LoggingException(String msg){
        super(msg);
    }
    private static Logger logger = Logger.getLogger("LoggingException");
    static void logException(Exception e){
        StringWriter trace = new StringWriter();
        e.printStackTrace(new PrintWriter(trace));
        logger.severe(trace.toString());
    }
}
public class TestLogger {
    public static void main(String[] args) {
        try{
            throw new LoggingException("Lo");
        }
        catch (LoggingException e){
            LoggingException.logException(e);
        }
    }
}

4月 11, 2020 10:47:23 下午 exceptionHandling.LoggingException logException
严重: exceptionHandling.LoggingException: Lo
	at exceptionHandling.TestLogger.main(TestLogger.java:22)

打印栈路径

class WhoCalled{
    static void f(){
        try{
            throw new Exception();
        }
        catch (Exception e){
            for(StackTraceElement stackTraceElement:e.getStackTrace()) {
                System.out.println(stackTraceElement.getMethodName());
            }
        }
    }
}


public class TestStackTrace {
    static void g(){
        WhoCalled.f();
    }
    static void h(){
        g();
    }
    public static void main(String[] args) {
        g();
        System.out.println();
        h();
    }
}

f
g
main

f
g
h
main

构造器抛出异常

构造时抛出的异常应该立即用catch单独处理,保证在后续操作中对象是已经创建完成的。

什么时候使用异常处理

  1. 在知道如何处理异常时,才处理
  2. 解决问题并且重新调用异常的方法
  3. 进行少许修补,然后绕过异常发生的地方继续进行
  4. 用别的数据计算解决异常
  5. 把当前环境下的事做完,向更高层抛出待解决的异常
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值