Java异常处理

1、格式

ArithmetricException("")
try(){
throw(ArithmetricException("");
}catch(){
 //输出的异常捕获错误
}

2、举个🌰

     public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入第一个数字");
    int firstNum = sc.nextInt();
    System.out.println("请输入第二个数字");
    int secondNum =sc.nextInt();

    try {

        if (secondNum==0)
            //可缺省
            //                throw new ArithmeticException("除数不能为0");
       System.out.println("Result:"+"number1"+"/"+"number2"+"="+firstNum/secondNum);


    }catch (ArithmeticException e){

        System.out.println("Excption:error,除数不能为0");
    }

    System.out.println("相除的结果是:");

}

3、常用的三个异常类型

ArithmeticException();
FileNotFoundException();
InputMismatchException();

所有异常类的根是:Throwable
异常类的三种主要类型:
1、系统错误:是由java虚拟机抛出的,用Error 类表示;描述的是内部系统错误;几乎很少发生
Error 类的子类:(免检异常)
LinkageError 、VirtualMachineError;
2、异常(exception)
用Exception类表示的,它描述的是由程序和外部环境引起的错误,这些错误能被程序捕获和处理;
Exception的子类:(必检异常)
ClassNotfoundException、IOException;
3、运行时异常(runtime exception)(免检异常)
是用RunTimeException 类表示的,描述的是程序设计错误,例如:错误的类型转换,访问一个数组越界或者树枝错误,运行时异常通常都是由Java虚拟机抛出的。
RunTimeException的子类:
ArithmeticException
NullPointerException
IndexOutOfBoundsException
IllegalArgumentException

4、方法使用异常捕获的声明

   public void myMethod ()  throws Exception1,Exception2,Exception3...

5、抛出异常

 IllegalArgumentException ex = new IllegalArgumentException("wrong ");
 throw(ex);

或者

   throw  new IllegalArgumentException("wrong ");

⚠️注意:声明异常的关键字是throws,抛出异常的关键字是throw;
6、捕获异常
try{
statement;
}
catch(Exception1 ex){

}

catch(Exception2 ex){

}

7、例子
异常方法位置打印

  public static void main(String[] args) {
    int sum = sum(new int[]{1,2,3,4,5});
    try {
        System.out.println(sum);
    }
    catch (Exception ex){
        ex.printStackTrace();;
        System.out.println("\n"+ex.getMessage());
        System.out.println("\n"+ex.toString());

        System.out.println("\n trace Info Obained from getStackTrace");
        StackTraceElement [] traceElements = ex.getStackTrace();
        for (int i = 0; i <traceElements.length ; i++) {
            System.out.println("method:"+traceElements[i].getMethodName());
            System.out.println("\n ClassName"+traceElements[i].getClassName());
            System.out.println("\n 行数"+traceElements[i].getLineNumber());
        }

    }

}


private  static  int sum(int [] sumArr){
    int result = 0;
    //这里设置一个错误,用于测试抛出异常
    for (int i = 0; i <=sumArr.length; i++) {
        result = result+sumArr[i];
    }
    return  result;

}

8、Finally 语句
用法:不论程序是否出现异常或者是否被捕获,都希望执行某些代码;

例子:I/O程序设计,用于最后关闭文件;

    public static void main(String[] args) {

    //定义局部变量
    java.io.PrintWriter outPut = null;

    try{
        outPut = new  java.io.PrintWriter("text.txt");
        outPut.println("welcome to java");
    }
    catch (java.io.IOException ex){
        System.out.println("error");
        ex.getStackTrace();
    }
    finally {
        if (outPut!=null)
            outPut.close();
        System.out.println("execute the finally statement");
    }
  System.out.println("end of program");

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 六种异常处理的陋习 你觉得自己是一个Java专家吗?是否肯定自己已经全面掌握了Java的异常处理机制?在下面这段代...
    Executing阅读 1,366评论 0 6
  • 2.JAVA异常 异常指不期而至的各种状况,如:文件找不到、网络连接失败、非法参数等。异常是一个事件,它发生在程...
    青城楼主阅读 570评论 0 0
  • 初识异常(Exception) 比如我们在取数组里面的某个值得时候,经常会出现定义的取值范围超过了数组的大小,那么...
    iDaniel阅读 1,884评论 1 2
  • Java异常类型 所有异常类型都是Throwable的子类,Throwable把异常分成两个不同分支的子类Erro...
    予别她阅读 956评论 0 2
  • 概念介绍 异常是发生在程序执行过程中阻碍程序正常执行的错误事件,当一个程序出现错误时,可能的情况有如下3种: 语法...
    niaoge2016阅读 5,216评论 2 20