java异常笔记

为什么会有异常

计算机不是万能的,程序猿也不是万能的,总会犯错误。

比如当我们编译时报错,或者代码能跑后出现数组越界

这就会出现异常;

异常有几种

两种,一种是编译时异常,另一种是运行时异常。

由图可见,所有的异常都继承自Throwable

编译时异常

受控异常,编译时就能看到

比如代码中的分号写成中文。

运行时异常

不受控异常,运行时才能看到

常见异常:

算数异常 数组越界异常 空指针异常

怎么用

try...catch...finally

int[] arr = {1, 2, 3};
try {
    System.out.println("before");
    arr = null;
    System.out.println(arr[100]);
    System.out.println("after");
} catch (Exception e) {
    e.printStackTrace();
} finally {
    System.out.println("finally code");
}

运行结果

抛出异常throws

public static void main(String[] args) { 
 System.out.println(divide(10, 0)); 
} 
public static int divide(int x, int y) { 
 if (y == 0) { 
 throw new ArithmeticException("抛出除 0 异常"); 
 } 
 return x / y; 
} 
// 执行结果
Exception in thread "main" java.lang.ArithmeticException: 抛出除 0 异常
 at demo02.Test.divide(Test.java:14) 
 at demo02.Test.main(Test.java:9)

我们可以使用 throws 关键字, 把可能抛出的异常显式的标注在方法定义的位置. 从而提醒调用者要注意捕获这些异常.

public static int divide(int x, int y) throws ArithmeticException { 
 if (y == 0) { 
 throw new ArithmeticException("抛出除 0 异常"); 
 } 
 return x / y; 
}

自定义异常

package org.example.excep;

public class MyException extends RuntimeException{
    public MyException(){
        super();
    }
    public MyException(String message){
        super(message);
    }

}
package org.example.excep;

import java.util.Scanner;

public class Testthrows {
    public static void main(String[] args)throws MyException{
        Scanner cin = new Scanner(System.in);
        int a = cin.nextInt();
        if(a==0){
            throw new MyException("this is a test");
        }
        System.out.println("after"); //不会执行!!!
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XSS9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值