【Java】异常处理

Throwable

Error

Error编译时不可检查,常见的StackOverflowError、OOMError

/**
 * @author:sy104
 * @date: 2021/11/28
 * @desc: Error是错误,对于所有的编译时期的错误以及系统错误都是通过Error抛出的
 */
public class ErrorDemo01 {
    public static void main(String[] args) {
        new ErrorDemo01().a();
        System.out.println("继续");
    }
    void a(){
        b();
    }
    void b(){
        a();
    }
}
Exception

运行时异常(不可检查异常):RuntimeException,不强制在编译期检查,但也可以主动throw

常见的ArithmeticException

/**
 * @author:sy104
 * @date: 2021/11/28
 * @desc: RuntimeException及其子类都是unchecked exception。
 *        比如NPE空指针异常,除数为0的算数异常ArithmeticException等等
 *        这种异常是运行时发生,无法预先捕捉处理的。Error也是unchecked exception,也是无法预先处理的。
 */
public class ExceptionDemo01 {
    public static void main(String[] args) {
        System.out.println(10/0);
        System.out.println("继续");
    }
}

可检查的异常:

/**
 * @author:sy104
 * @date: 2021/11/28
 * @desc: 可检查的异常,这是编码时非常常用的,所有checked exception都是需要在代码中处理的。
 *        它们的发生是可以预测的,正常的一种情况,可以合理的处理。比如IOException,或者一些自定义的异常。
 *        除了RuntimeException及其子类以外,都是checked exception。
 *        不处理无法通过编译:未报告的异常错误java.lang.InterruptedException; 必须对其进行捕获或声明以便抛出
 */
public class ExceptionDemo02 {
    public static void main(String[] args) throws InterruptedException {
        Thread.sleep(1);
    }
}

throw的用法:

/**
 * @author:sy104
 * @date: 2021/11/28
 * @desc: throw出去,下面的不会执行。
 */
public class ThrowDemo01 {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        if (b == 0) {
            throw new ArithmeticException();
        }
        System.out.println(10 / 0);

        System.out.println("继续");
    }
}

try catch的用法

/**
 * @author:sy104
 * @date: 2021/11/28
 * @desc: 用try catch处理完异常后,程序可以继续执行
 */
public class ThrowDemo02 {
    public static void main(String[] args) {
        try {
            new ThrowDemo02().foo();
        } catch (Exception e) {
            System.out.println("捕获到异常");
        }
        System.out.println("继续");
    }
    void foo() throws Exception{
        System.out.println(10/0);
    }
}

/**
 * @author:sy104
 * @date: 2021/11/28
 * @desc: 尝试捕获Error,使用catch(Exception)无法捕获
 *        但是使用catch(Error或Throwable)可以捕获
 *        程序总会执行finally
 */
public class TryDemo01 {
    public static void main(String[] args) {

        try {
            new ErrorDemo01().a();
        } catch (Throwable e) {
            e.printStackTrace();
        }finally {
            System.out.println("finally");
        }
        System.out.println("继续");
    }
    void a(){
        b();
    }
    void b(){
        a();
    }
}
/**
 * @author:sy104
 * @date: 2021/11/28
 * @desc: System.exit(0);之后的finally不会执行 
 * ArithmeticException处理后,Exceptionb不catch
 */
public class TryDemo03 {
    public static void main(String[] args) {
        try {
            System.out.println(10/0);
        }catch (Error e) {
            System.out.println("Error");
        }catch (ArithmeticException e) {
            System.out.println("Exception");
            //System.exit(0);
        } catch (Exception e) {
            System.out.println("Exception");
            System.exit(0);
        } finally {
            System.out.println("finally");
        }
        System.out.println("继续");
    }
}

自定义异常

可以写一个自己的登录验证Exception,继承RuntimeException

/**
 * @author:sy104
 * @date: 2021/11/28
 * @desc: 自定义异常BaseException,继承RuntimeException,自定义的BaseException应该提供多个构造方法:
 */
public class BaseException extends RuntimeException {

    public BaseException() {
        super();
    }

    public BaseException(String message, Throwable cause) {
        super(message, cause);
    }

    public BaseException(String message) {
        super(message);
    }

    public BaseException(Throwable cause) {
        super(cause);
    }

}
public class LoginFailedException  extends BaseException {
    public LoginFailedException() {
    }

    public LoginFailedException(String message) {
        super(message);
    }
}
public class UserNotFoundException extends BaseException {
    public UserNotFoundException() {
    }

    public UserNotFoundException(String message) {
        super(message);
    }
}

测试:

/**
 * @author:sy104
 * @date: 2021/11/28
 * @desc: 验证不通过就throw出对应的LoginFailedException
 */
public class MyExceptionDemo {
    public static void main(String[] args) {
        String token = login("admin", "pass");
        System.out.println("Token: " + token);
    }

    static String login(String username, String password) {
        if (username.equals("admin")) {
            if (password.equals("password")) {
                return "xxxxxx";
            } else {
                // 抛出LoginFailedException:
                throw new LoginFailedException("Bad username or password.");
            }
        } else {
            // 抛出UserNotFoundException:
            throw new UserNotFoundException("User not found.");
        }
    }
}
总结

Java异常提供了对异常的处理手段,提高了程序的健壮性,而不是遇到一点问题就结束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值