java异常处理

来源:互联网 发布:卡尔曼滤波原理和算法 编辑:程序博客网 时间:2024/06/01 18:58

java异常处理

异常:程序在运行时出现的一些不正常的情况

异常由来:对于出现的不正常的情况,java通过类进行描述,并封装成对象。

异常分为两类:

一、严重的,由error类进行描述,一般不通过写针对性解决代码

二、不严重的,由exception类进行描述,通过写针对性代码解决


error类和exception类的父类都是thowable类

thowable

Error

Exception

异常代码

class ExceptionTest{int[] show(int x){int[] a = new int[x];for(int i = 0 ; i < a.length ; i++){a[i] = i + 1;}return a;}}public class ExceptionDemo {public static void main(String[] args){int[] a = new ExceptionTest().show(-1);for(int i = 0 ; i < a.length ; i++){System.out.println(a[i] + "  ");}}}

异常处理:

java提供了特有的语句进行处理

try{

出现异常的代码

}catch(异常类 变量){

处理异常的代码

}finally{

一定会执行的代码

}


class ExceptionTest{int[] show(int x){int[] a = new int[x];for(int i = 0 ; i < a.length ; i++){a[i] = i + 1;}return a;}}public class ExceptionDemo {public static void main(String[] args){try {int[] a = new ExceptionTest().show(-1);for(int i = 0 ; i < a.length ; i++){System.out.println(a[i] + "  ");}} catch (Exception e) {// TODO: handle exceptionSystem.out.println("数组长度不能为负数");}}}




0 0