SE在澳註冊新商標 被猜測與《勇氣默示錄2》有關
異常處理
異常處理常見手段: try catch finally throws
1.try catch
1.將可能丟擲FileNotFoundException 檔案不存在異常的程式碼放在try裡
2.如果檔案存在,就會順序往下執行,並且不執行catch塊中的程式碼
3. 如果檔案不存在,try 裡的程式碼會立即終止,程式流程會執行到對應的catch塊中
4. e.printStackTrace(); 會打印出方法的呼叫痕跡,
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class rubbish {
public static void main(String args[]){
File f= new File("d:/LOL.exe");
try{
System.out.println("試圖開啟 d:/LOL.exe");
new FileInputStream(f);
System.out.println("成功開啟");
}
catch (FileNotFoundException e){
System.out.println("d:/LOL.exe不存在");
e.printStackTrace();
}
}
}
2.使用異常的父類進行catch
FileNotFoundException是Exception的子類,使用Exception也可以catch住FileNotFoundException
例如在上面的程式碼中,在catch的引數中,用Exception代替FileNotFoundException
3.多異常捕捉辦法
有的時候一段程式碼會丟擲多種異常,解決辦法之一就是寫多個catch
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class rubbish {
public static void main(String args[]){
File f = new File("d:/LOL.exe");
try {
//檔案異常程式碼
System.out.println("試圖開啟 d:/LOL.exe");
new FileInputStream(f);
System.out.println("成功開啟");
//日期異常的程式碼
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = sdf.parse("2016/06-03");
} catch (FileNotFoundException | ParseException e) {
if (e instanceof FileNotFoundException)
System.out.println("d:/LOL.exe不存在");
if (e instanceof ParseException)
System.out.println("日期格式解析錯誤");
e.printStackTrace();
}
}
}
4.finally
無論是否出現異常,finally中的程式碼都會被執行
5.throws
throws:把異常拋給上一個函式
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class rubbish {
public static void main(String[] args) {
method1();
}
private static void method1() {
try {
method2();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void method2() throws FileNotFoundException {
File f = new File("d:/LOL.exe");
System.out.println("試圖開啟 d:/LOL.exe");
new FileInputStream(f);
System.out.println("成功開啟");
}
}
throw和throws的區別
throws與throw這兩個關鍵字接近,不過意義不一樣,有如下區別:
- throws 出現在方法宣告上,而throw通常都出現在方法體內。
- throws 表示出現異常的一種可能性,並不一定會發生這些異常;throw則是丟擲了異常,執行throw則一定丟擲了某個異常物件。
6.練習
假設有一個方法 public int method(), 會返回一個整數
在這個方法中有try catch 和 finally.
try 裡返回 1
catch 裡 返回 2
finally 裡 返回3
那麼,這個方法到底返回多少?
對練習的理解:
其實在try中遇到return後,系統會將return的值儲存在一個區域中,然後如果有finally就執行finally裡的程式碼,如果又遇到了return,就會將最後這個return值覆蓋原來的那個值,在返回給呼叫者
package pack6;
public class Except {
static public int method(){
try {
return 1;
}catch (Exception e){
return 2;
}finally {
return 3;
}
}
static public void main(String args[]){
System.out.println(method());//返回3
}
}