/*
finally代码块:定义一定执行的代码。
通常用于关闭资源。
*/
class FuShuException extends Exception
{
FuShuException(String msg)
{
super(msg);
}
}
class Demo
{
int div(int a,int b)throws FuShuException
{
if(b<0)
throw new FuShuException("除数为负数");
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="+x);
}
catch (FuShuException e)
{
System.out.println(e.toString());
return;
//System.exit(0);//系统,退出。jvm结束。
}
finally
{
System.out.println("finally");//finally中存放的是一定会被执行的代码。
}
System.out.println("over");
}
}
class NoException extends Exception
{
}
public void method()throws NoException
{
连接数据库;
数据操作;//throw new SQLException();
关闭数据库;//该动作,无论数据操作是否成功,一定要关闭资源。
try
{
连接数据库;
数据操作;//throw new SQLException();
}
catch (SQLException e)
{
会对数据库进行异常处理;
throw new NoException();
}
finally
{
关闭数据库;
}
}
第一个格式:
try
{
}
catch ()
{
}
第二个格式:
try
{
}
catch ()
{
}
finally
{
}
第三个格式:
try
{
}
finally
{
}
//记住一点:catch是用于处理异常。如果没有catch就代表异常没有被处理过,如果该异常是检测时异常。那么必须声明。
class Demo
{
public void method()
{
try
{
throw new Exception();
}
finally
{
//关资源。
}
}
}
class
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
/*
异常在子父类覆盖中的体现;
1,子类在覆盖父类时,如果父类的方法抛出异常,那么子类的覆盖方法,只能抛出父类的异常或者该异常的子类。
2,如果父类方法抛出多个异常,那么子类在覆盖该方法时,只能抛出父类异常的子集。
3,如果父类或者接口的方法中没有异常抛出,那么子类在覆盖方法时,也不可以抛出异常。
如果子类方法发生了异常。就必须要进行try处理。绝对不能抛。
*/
class AException extends Exception
{
}
class BException extends AException
{
}
class CException extends Exception
{
}
/*
Exception
|--AException
|--BException
|--CException
*/
class Fu
{
void show()throws AException
{
}
}
class Test
{
void function(Fu f)
{
try
{
f.show();
}
catch (AException e)
{
}
}
}
class Zi extends Fu
{
void show()throws CException
{
}
}
class
{
public static void main(String[] args)
{
Test t = new Test();
t.function(new Zi());
}
}
/*
有一个圆形和长方形。
都可以获取面积。对于面积如果出现非法的数值,视为是获取面积出现问题。
问题通过异常来表示。
现有对这个程序进行基本设计。
*/
class NoValueException extends RuntimeException
{
NoValueException(String message)
{
super(message);
}
}
interface Shape
{
void getArea();
}
class Rec implements Shape
{
private int len,wid;
Rec(int len ,int wid)//throws NoValueException
{
if(len<=0 || wid<=0)
throw new NoValueException("出现非法值");
this.len = len;
this.wid = wid;
}
public void getArea()
{
System.out.println(len*wid);
}
}
class Circle implements Shape
{
private int radius;
public static final double PI = 3.14;
Circle(int radius)
{
if(radius<=0)
throw new NoValueException("非法");
this.radius = radius;
}
public void getArea()
{
System.out.println(radius*radius*PI);
}
}
class ExceptionTest1
{
public static void main(String[] args)
{
Rec r = new Rec(3,4);
r.getArea();
Circle c = new Circle(-8);
System.out.println("over");
}
}