/*
* finally代码快:定义一定执行的代码。
* 通常用于关闭资源, 如关闭数据库
*
* 异常语句有三种形式
* 1,try catch 可以有多个atch
* 2, try catch finally
* 3, try finally
* 异常在子父类覆盖中的体现:
* 1、子类在覆盖父类时,如果父类方法抛出异常,那么子类的覆盖方法,只能抛出父类的异常或者该异常的子类
* (子类抛出的异常必须是父类有的)
* 2、如果父类方法抛出多个异常,那么子类在覆盖该方法时,只能抛出父类异常的子集
* 3,如果父类或者接口的方法中没有异常抛出,那么子类在覆盖方法时,也不可以抛出异常,
* 如果子类方法发生了异常,就必须要进行try 处理,绝对不能抛。
*/
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("出现负数了");//抛出的时编译时检测的异常
}
if(b==0){
throw new FuShuException("出现零了");
}
return a/b;
}
}
public class D_Exp_Finally {
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());
}
finally{
System.out.println("finally");//这是异常与否都会出现的代码。
}
}
}
---------------------------------------------------------------------------------------------------------
package _Day10;
/*
【异常练习】
有一个圆形和长方形
都可以获取面积,对于面积如果出现非法数值,视为是货获取面积出现的问题
问题通过异常来表示
先有对这个程序进行基本设计
正常代码,和问题处理代码分隔开。
写代码的过程中,遇到问题,用代码封装起来,问题也是一个对象。
*/
//面积接口
interface Shape{
double getArea();
}
//负数或零异常
class FLException extends
RuntimeException //Exception
{
FLException(String msg){
super(msg);
}//
}
//长方形
class Rec implements Shape{
private int len,wid;
Rec(int len,int wid) //throws FLException //使用Runtaime异常这里就不用在写,main方法中也不用在写。
{
if(len<=0 ||wid<=0)
throw new FLException("数值错误!");
this.len=len;
this.wid=wid;
}
public double getArea(){
System.out.println("Area:"+len*wid);
return len*wid;
}
}
//圆形
class Yuan implements Shape{
private double r;
private static final double PI=2.14; //设为全局常量
Yuan(double r){
if(r<=0)
throw new FLException("非法!");
this.r=r;
}
public double getArea(){
System.out.println("Area:"+r*r*PI);
return r*r*PI;
}
}
public class D_Exp_Test1 {
public static void main(String[] args) {
Rec r=new Rec(23,4);
r.getArea();
Yuan yu=new Yuan(-3);
yu.getArea();
}
}
---------- android培训、 java培训 、期待与您交流!----------
黑马官网: http://edu.csdn.net/heima