zoukankan      html  css  js  c++  java
  • 异常


    编译时异常又叫受检时异常,运行时异常又叫非受检时异常.开发中编译时异常可以用try-catch-finally处理将其转为运行时异常,对于运行时异常用throws比较好,抛出异常给上一级处理。
    异常处理

    • error:Java虚拟机无法解决的异常,如stackOverflowError.
    • exception
    • try-catch-finally,可以写多个catch异常,若多个异常之间存在关系,则子类异常在父类上面。
    try{
                int a = 10;
                int b = 0;
                System.out.println(a / b);
            }catch (ArithmeticException e){
                System.out.println("异常");
            }finally {
                System.out.println("finally");
            }
    //结果:异常    finally
    try{
                int a = 10;
                int b = 0;
                System.out.println(a / b);
                return 1;
            }catch (ArithmeticException e){
                System.out.println("异常");
                return 2;
            }finally {
                System.out.println("finally");
                return 3;
            }
          int a = Test4();
          System.out.println(a);
    //结果: 异常   finally   3
    
    • throws
    //如:
    if(a > 0)
       //dosomething;
    else
       throw new RuntimeException(); //运行时异常,编译时不报错
       //throw new Exception();   编译时报错
    
    • throw手动抛出异常
      子类重写的方法抛出的异常不大于父类异常
    • 自定义异常:让该类继承Exception / RuntimeException...
    //example
    class MyException extends Exception{
    
    }
    
  • 相关阅读:
    快排 [模板]
    翻硬币
    Euphoria与量子波动速读
    高精度例题
    Div3 595 E
    Div 595 C1 C2
    常用 STL 整理
    CF 595 Div3 B2
    【思维】复杂度均摊+并查集——icpc cerc 2019 Saba1000kg
    离散化+圆直线交点+转化——icpc cerc 2019 D
  • 原文地址:https://www.cnblogs.com/huyuqing/p/14286597.html
Copyright © 2011-2022 走看看