异常

异常
所有的异常都是继承自Throwable类,异常又分为Error和Exception。
Error:指Java运行时系统的内部错误和资源耗尽错误。
Exception:分为RuntimeException和IOException。
自定义异常

import java.util.Scanner;

class exception extends Exception{
    public exception(){}
    public exception(String s){
        super(s);
    }
}
public class TestDemo5{
    public static void fun1() throws exception {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        if(a <= 0){
            throw new exception("异常");
        }
    }
    public static void main(String[] args) throws exception {
        fun1();

    }
}

捕获异常
try…catch块:

 public static void fun()throws ArithmeticException{
        try {
            int a = 10;
            int b = 0;
            int c = a/b;
            System.out.println(c);
        }catch (ArithmeticException e){
            System.out.println("运算异常");
            e.printStackTrace();//打印异常信息栈
        }

    }
 public static void fun3(){
        try {
            String str = "abcdef";
            System.out.println(str.charAt(6));
        }catch (StringIndexOutOfBoundsException e){
            System.out.println("字符串越界异常");
            e.printStackTrace();//打印异常信息栈
        }

}

try…catch finally:

  public static void Calculate () //这里已经处理了异常,不需要再声明异常了
//如果加了声明,当前函数就不处理了,调用该函数的一方进行处理。
    {
        Scanner scan = new Scanner ( System. in );
        try {
            int num1 = scan .nextInt () ;
            int num2 = scan .nextInt () ;
            int result = num1/num2 ;
            System . out. println( "result:" + result) ;
        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException 异常");
            e.printStackTrace();
        } catch (InputMismatchException e) {//输入有误的时候
            System.out.println("InputMismatchException 异常");
            e.printStackTrace();
        } finally {
            scan .close ();//释放资源
        }
    }

警告:当finally子句包含return语句时,将会出现一种意想不到的结果,假设利用return语句从try语句中退出,在方法返回前,finally子句的内容将被执行。如果finally子句中也有一个return语句,这个返回值将会覆盖try语句中的返回值。

public int fun2(){//该方法返回的值为3,因为finally中的方法覆盖了try...catch块中的return
        try{
            return 1;
        }catch (Exception e){
            return 2;
        }finally {
            return 3;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值