Java教程

异常抛出和捕获

本文主要是介绍异常抛出和捕获,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

异常处理机制

  • 抛出异常

  • 捕获异常

异常处理的五个关键字

try,catch,finally,throw,throws

package exception;
​
public class test {
    public static void main(String[] args) {
        int a=0;
        int b=1;
        //假设要捕获多个异常要从小到大的写
        try {//try监控区域
            if (a==0){
                throw new ArithmeticException();
            }
            System.out.println(b/a);
        }catch (Exception e){//catch捕获异常
            System.out.println("格式错误");
​
        }catch (Throwable e){
            System.out.println("严重错误");
        }
        finally {//处理善后工作
            System.out.println(123);
            //finally 可以不要finally,假设io资源关闭
​
        }
    }
    public void a(){
        b();
    }
    public void b(){
        a();
    }
}
package exception;
​
public class test3 {
    public static void main(String[] args) {
        new test3().add(1,0);
​
    }
    public void add(int a , int b)throws ArithmeticException{
        if (b==0){
            throw new ArithmeticException();
        }
        System.out.println(a/b);
    }
}
package exception;
​
public class Test2 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        //自动生成 ctrl + alt + T
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

这篇关于异常抛出和捕获的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!