异常

简介: 异常

常见的运行时异常(runTimeException):

NullPointerException - 空指针引用异常

ClassCastException - 类型强制转换异常。

IllegalArgumentException - 传递非法参数异常。

ArithmeticException - 算术运算异常

ArrayStoreException - 向数组中存放与声明类型不兼容对象异常

IndexOutOfBoundsException - 下标越界异常

NegativeArraySizeException - 创建一个大小为负数的数组错误异常

NumberFormatException - 数字格式异常

SecurityException - 安全异常

UnsupportedOperationException - 不支持的操作异常

try……catch语法

  try {
      //正常代码块
      int result = num1/num2;
      System.out.println(result);
    } catch (ArithmeticException e) {
      //算数异常,出现异常执行的代码块
      //e.fillInStackTrace();
      System.out.println("异常");
    }finally {
      //无论是否出现异常,finally内语句都会执行此代码块
      System.out.println("释放资源");
    }

错误代码

//编译错误
public static void main(String[] args) {
     try {    
           System.out.println(10 / 0);   
       } catch (RuntimeException e) {  
          System.out.println("RuntimeException");   
       } catch (ArithmeticException e) {
       //ArithmeticException是RuntimeException的子类
       //在第一个catch中就是运行时异常处理了  
          System.out.println("ArithmeticException");
       }  
  }

输出结果为2

 int x = 0;
        try{
            x = div(5,2);
        }catch(Exception e){
            System.out.println(e);//输出的e空白对象,
        }
        System.out.println(x);//输出语句
    }
    public static int div(int a,int b){
        return a / b ;
    }
目录
相关文章
|
3月前
|
SQL 安全 程序员
C++:异常
C++:异常
39 7
|
3月前
|
安全 Java 编译器
异常的讲解
异常的讲解
31 1
|
安全 Java 程序员
c++异常
c++异常
84 0
|
3月前
|
SQL 安全 Java
C++之异常
C++之异常
16 0
|
3月前
|
C++
C++中的异常
C++中的异常
|
10月前
|
安全 程序员 C语言
|
10月前
|
Java 程序员 测试技术
C++11 异常(下)
C++11 异常(下)
48 0
|
Java 索引
05-异常
异常:Java代码在运行时期发生的问题叫做异常,当发生问题时,就会创建异常对象并抛出异常信息(异常的原因及位置)
91 0
05-异常
|
Java 程序员 编译器
理解并处理异常
理解并处理异常
74 0
理解并处理异常