------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
异常类
注意:如果让一个类成为异常类,必须继承异常体系,因为只有成为异常类才能被关键字 throws throw
异常的分类:
1:编译时被检测异常,主要是Exception 和其子类(除 RuntimeException)
这种问题一旦出现,希望在编译时就进行检测,让这种问题有对应的处理方式
这种问题都可以针对性的处理。
2:编译时不检测异常(运行时异常):就是RuntimeException 及其子类。
这种问题发生,无法让功能继续,大多是因为调用者的原因导致
这种问题一般不处理,直接编译通过,在运行时,让调用哪个最调用时的程序强制停止,让调用者对代码进行修正
异常处理的捕捉形式:
这是可以对异常进行针对性处理的方式。
具体格式:
try
{
//需要被检测异常的代码
}
catch(异常类变量)//该变量用于接收发生的异常对象
{
//处理异常的代码。
}
finally //通常用于关闭(释放)资源
{
//一定会被执行的代码。
}
异常处理原则
1:函数内部如果抛出需要检测的异常,那么函数上必须要添加声明,或者必须在函数内用try catch捕捉,否则编译失败。
2:功能内容可以解决,用catch
解决不了,用throws告诉调用者,由调用者解决。
3:一个功能如果抛出多个异常,那么调试时,必须有对应多个catch进行针对性的处理。
抛出几个,就catch几个。
异常应用演示
class Fushuindex extends RuntimeException //继承的Exception时,需要throws Fushuindex (添加捕捉自定义声明)
{
Fushuindex(String a)
{
super(a); //直接调用父类的方法
}
}
class Demo
{
public int method(int [] arr , int index) //继承的Exception时,需要throws Fushuindex (添加捕捉自定义声明)
{
if(arr==null)
throw new NullPointerException("数组的角标不能为空");
if(index >=arr.length) //判断问题
throw new ArrayIndexOutOfBoundsException("数组角标越界了: "+index); //自定义异常返回信息
else if(index < 0)
throw new Fushuindex("数组角标不能小于0: ");
else
return arr[index]
}
}
class ExceptionDemo
{
public static void main(String[] args) //继承的Exception时,需要throws Fushuindex (添加捕捉自定义声明)
{
int [] a = new int [3];
Demo d = new Demo();
int num1 = d.method(a,1);
System.out.println("Hello World!"+num1);
//以下演示异常捕捉
//多catch时,父类catch必须放在最下面
try
{
int num2 = d.method(a,-30);
System.out.println("num2 = "+num2);
}
catch (Fushuindex x)
{
System.out.println("负数角标异常");
System.out.println(x.toString()); //异常信息
}
catch (Exception e)
{}
System.out.println("over");
}
}