一、RuntimeException
Exception中有一个特殊的子类异常RuntimeException运行时异常如果在函数内部抛出该异常,函数上可以不用申明,编译一样通过;如果在函数上申明了该异常,调用者可以不用进行处理(try catch),编译也一样通过。之所以不用在函数上申明,是因为不需要调用者来处理
当该异常发生时,希望程序停止,因为在运行时,出现了无法运行的情况我希望停止程序后,对代码进行改进。
自定义异常,如果该异常发生,无法进行运算时,就让自定义继承RuntimeException
异常分两种:
1.编译时期被检测异常;
2.编译时期不被检测异常(运行时异常,RuntimeException以及子类)。
程序代码如下:
classFushuException extends ArithmeticException
{
private int value;
FushuException(String msg)
{
super(msg);
}
}
class Demoextends ArithmeticException
{
public int div(int a,int b) //throwsArithmeticException
{
if(b<0)
throw newFushuException("被负数除啦!");
if(b==0)
throw newArithmeticException("被零数除啦!");
return a/b;
}
}
class ExceptionDemo4
{
public static void main(String[] args)
{
Demo d = new Demo();
int x = d.div(4,-1);
System.out.println(x);
}
}
二、Finally
finally代码块,定义一定执行的代码。通常用于关闭资源
public void method() throws NoException //注意这里不能抛出SQLException异常,因为调用者处理不了。需要内部进行问题封装成调用者能处理的异常。
{
//连接数据库
//操作数据 //thrownew SQLException数据库异常(出现异常函数自动结束,无法进行后面的语句,即不能关闭数据库)
//关闭数据库 //数据库一定要关闭,该语句必须执行
try
{
//连接数据库
//操作数据
}
catch (SQLException e)
{
//数据库异常处理
throw newNoException();//分层处理,问题封装
}
}
程序代码如下:
classNoException extends Exception
{
}
classFushuException extends ArithmeticException
{
private int value;
FushuException(String msg)
{
super(msg);
}
}
class Demoextends ArithmeticException
{
public int div(int a,int b) //throwsArithmeticException
{
if(b<0)
throw newFushuException("被负数除啦!");
if(b==0)
throw newArithmeticException("被零数除啦!");
return a/b;
}
}
class ExceptionDemo5
{
public static void main(String[] args)
{
Demo d = new Demo();
try
{
int x = d.div(4,1);
System.out.println(x);
}
catch (ArithmeticException e)
{
System.out.println(e.toString());
}
finally
{
System.out.println("Finally");
}
}
三、异常处理的三种格式
异常处理的三种格式
第一种:
try
{
}
catch ()
{
}
第二种
try
{
}
finally ()
{
}
第三种
try
{
}
catch ()
{
}
finally
{
}
四、总结:
1、catch是处理异常的方式,如果没有Catch就代表异常没有被处理。
如果异常被检测没有被处理,那必须被声明。
2、异常在子父类中的体现:
a.子类在覆盖父类时,如果父类的方法抛出异常,那么子类的覆盖方法,只能抛出父类的异常或者该异常的子类。
b.如果父类方法抛出多个异常,那么子类在覆盖方法是,只能抛出父类异常的子集。
c.如果父类或者接口中没有异常抛出时,那么子类在覆盖方法时,也不可以抛出异常。
如果子类出现异常时,那么必须try处理掉,绝对不能抛出。