/*
* 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