java异常包含几大块
object
|------Throwable
|-----Error :通常是jvm抛出的错误(内存不足,找不到类。。。。)
|------Exception : 代码运行过程中产生的异常
|---------RuntimeException :在Exception比较特殊的异常,通常不用声明,一般在编译时不进行检测的异常(例NullPointerException)
|---------除RuntimeException 外的Exception,通常要声明,然后进行异常处理(自定义类往往使用这种方法)
一些代码例子
class FuShuIndexException extends Exception
{
FuShuIndexException()
{}
FuShuIndexException(String msg)
{
super(msg);
}
}
class Demo
{
public int method(int[] arr,int index)//throws NullPointerException//FuShuIndexException
{
if(arr==null)
throw new NullPointerException("数组的引用不能为空!");
if(index>=arr.length)
{
throw new ArrayIndexOutOfBoundsException("数组的角标越界啦,哥们,你是不是疯了?:"+index);
}
if(index<0)
{
throw new FuShuIndexException("角标变成负数啦!!");
}
return arr[index];
}
}
class ExceptionDemo3
{
public static void main(String[] args) //throws FuShuIndexException
{
int[] arr = new int[3];
Demo d = new Demo();
int num = d.method(null,-30);
System.out.println("num="+num);
System.out.println("over");
}
}
异常转换:底层异常,中层捕捉到,预处理,转化成更通熟易懂的信息继续throw到上层,上层再处理
public class TestException {
public static void main(String[] args)
{
Teacher t = new Teacher("毕老师");
try
{
t.prelect();
}
catch (NoPlanException e)
{
System.out.println(e.toString()+"......");
System.out.println("换人");
}
}
}
class LanPingException extends Exception
{
LanPingException(String msg)
{
super(msg);
}
}
class MaoYanException extends Exception
{
MaoYanException(String msg)
{
super(msg);
}
}
class NoPlanException extends Exception
{
NoPlanException(String msg)
{
super(msg);
}
}
class Computer
{
private int state = 2;
public void run()throws LanPingException,MaoYanException
{
if(state==1)
throw new LanPingException("电脑蓝屏啦!!");
if(state==2)
throw new MaoYanException("电脑冒烟啦!!");
System.out.println("电脑运行");
}
public void reset()
{
state = 0;
System.out.println("电脑重启");
}
}
class Teacher
{
private String name;
private Computer comp;
Teacher(String name)
{
this.name = name;
comp = new Computer();
}
public void prelect()throws NoPlanException
{
try
{
comp.run();
System.out.println(name+"讲课");
}
catch (LanPingException e)
{
System.out.println(e.toString());
comp.reset();
prelect();
}
catch (MaoYanException e)
{
System.out.println(e.toString());
test();
//可以对电脑进行维修。
// throw e;
throw new NoPlanException("课时进度无法完成,原因:"+e.getMessage());
}
}
public void test()
{
System.out.println("大家练习");
}
}