异常处理的代码简单,重要还是理解其思想
一.概述:
Throwable:
Error
通常出现重大问题如,运行的类不存在或者内存溢出等
不编写针对代码对其处理
Exception
在运行时运行出现的一起情况,可以通过trt catch finally
class Futime
{
}
class Bigtime
{
}
public class Main
{
public static void main(String[] args)
{
/*int[] a = new int[5];
* a = null;
System.out.println(a[5]);//异常
*/
sleep(-5);
}
/*public static void sleep(int t)
{
if(t<0)
{
//数据出错,处理办法
//数据出错,处理办法
//数据出错,处理办法
//.....阅读性差
修正见下
}
else if(t>10000)
{
//数据出错,处理办法
//数据出错,处理办法
//数据出错,处理办法
new Bigtime();
}
else {
System.out.print("休息"+t+"分种");
}
}*/
public static void sleep(int t)//这样就清晰很多
{
if(t<0)//但是注意就有个问题,谁在调用这个功能,如何收到异常呢
{//采用抛出的方式
抛出 new Futime();//代表时间为负情况,这个对象中包含着问的名称,信息,位置等信息
}
else if(t>10000)//比如:我感冒了
{
抛出 new Bigtime();//C是吃药,上医院...,而java就可以理解找治感冒的方法
}
else {
System.out.print("休息"+t+"分种");
}
}
}二.异常体系
如果问题很多就意味着描述的类以前很多
将其共性进行向上抽取,就形成了异常体系
最终问题(不正常情况)就分成了两大类
Throwable://无论是error,还是异常问题,问题发生就应该可以抛出,让调用者知道并处理 ->可抛性
(父类下面有两大派 )
1.一般不可处理的。用Error类表示
2.可以处理的。用Exception
体系特点:
Throwable及其所有子类都具有可抛性,不是这体系的不行
如何体现可抛性?
通过两个关键字:throws和throw,凡是被这两个关键字所操作的类和对象都具备可抛性
(Error和Exception类似于疾病,可以治愈的,和不可以治愈的)
Error:
特点:是由JVM抛出的严重性的问题,已经影响到程序的运行了
这种问题的发生一般不针对性处理,因为处理不了,直接修改程序(int[] a = new int[1024*1024*800],开辟一个800M的数组)
Exception的直接子类很多,Error的直接子类不多,但是都是不可处理的,比较狠
体系的特点:
子类的后缀名都是用其父类名作为后缀,阅读性强,比如OutOfMemoryError
三、原理及其异常对象的抛出
小演示:
class ExceptionDemo
{
public int method(int[] arr,int index)
{
if(arr==null)
throw new NullPointerException("数组引用怎么能为空呢?");
if(index>=arr.length)
{
//return -1;为什么不写return,因为跟本就不运算
throw new ArrayIndexOutOfBoundsException("数组角标越界"+index);
//throw new ArrayIndexOutOfBoundsException(""+index);//默认的
}
if(index<0)
{
throw new ArrayIndexOutOfBoundsException("数组角标不能为负"+index);
}
return arr[index];
}
}
public class Main
{
public static void main(String[] args)
{
int[] a = new int[10];
ExceptionDemo C = new ExceptionDemo();
int num = C.method(a,20);
//int num = C.method(null,2);
System.out.print("num"+num);
}
}class FuException extends Exception
{
FuException()
{
}
}
//定义一个异常后,需要告诉调用者可能出现的问题
class ExceptionDemo
{//要么捕捉,要么抛出
public int method(int[] arr,int index) throws FuException
{
if(index<0)
{
throw new FuException();
}
return arr[index];
}
}
public class Main
{
public static void main(String[] args)throws FuException
{
int[] a = new int[10];
ExceptionDemo C = new ExceptionDemo();
int num = C.method(a,-2);
System.out.print("num"+num);
}
}原文:http://blog.csdn.net/wjw0130/article/details/39625725