Java基礎之:例外及例外處理
我們將java程式執行程序中出現的不正常現象稱為例外,例如:之前遇到的陣列下標越界例外,空指標例外等等
執行程序中發生的例外事件分為兩類:
Error(錯誤):Java虛擬機無法解決的嚴重問題,如:JVM系統內部錯誤,資源耗盡等嚴重情況,比如:StackOverFlowError(堆疊溢位),Error是嚴重錯誤,程式會直接崩潰掉,
Exception:其他因為編程錯誤或偶然的外在因素導致的一般性問題,可以使用針對性的代碼進行處理,例如空指標訪問等,Exception分為兩大類:運行時例外(在程式運行程序中)、編譯時例外(在程式編譯程序中)


常見的運行時例外
NullPointerException:空指標例外
public class NullPointerException_ {
private static String str;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(str.length());
System.out.println("hello~");
}
?
}
ArithmeticException:數學運算例外
當出現例外的運算條件時,拋出此例外,例如,一個整數“除以零”時,拋出此類的一個實體, 例如:int i = 10 / 0
ArrayIndexOutOfBoundsException:陣列下標越界例外
public class ArrayIndexOutOfBoundsException_ {
?
public static void main(String[] args) {
?
int[] arr = {1,2};
System.out.println(arr[4]);
}
ClassCastException:型別轉換例外
當試圖將物件強制轉換為不是實體的子類時,拋出該例外,例如,以下代碼將生成一個 ClassCastException
public class ClassCastException_ {
?
public static void main(String[] args) {
Animal a = new Dog();
Cat cat = (Cat)a;
}
?
}
?
?
class Animal {
}
class Dog extends Animal {
}
class Cat extends Animal {
}
NumberFormatException:數字格式不正確例外
當應用程式試圖將字串轉換成一種數值型別,但該字串不能轉換為適當格式時,拋出該例外 => 使用例外我們可以確保輸入是滿足條件數字.
public class NumberFormatException_ {
public static void main(String[] args) {
String name = "小范~";
int num = Integer.parseInt(name);
}
}
常見的編譯時例外
-
SQLException //操作資料庫時,查詢表可能發生例外
-
IOException //操作檔案時,發生的例外
-
FileNotFoundException //當操作一個不存在的檔案時,發生例外
-
ClassNotFoundException //加載類,而該類不存在時,例外
-
EOFException // 操作檔案,到檔案末尾,發生例外
-
IllegalArguementException //引數例外
例外處理
例外處理就是當例外發生時,對例外處理的方式,
兩種方式:
-
try-catch-finally
程式員在代碼中捕獲例外,并自行處理
-
throws
將發生的例外拋出給呼叫方,最頂級的呼叫方就是JVM
try-catch例外處理
Java提供try和catch塊來處理例外,try塊用于包含可能出錯的代碼,catch塊用于處理try塊中發生的例外,可以根據需要在程式中有任意數量的try...catch塊,
基本語法:
try{
//可能出現例外的代碼
//將例外生成對應的例外物件,作為引數傳遞給catch
}catch(例外物件){
//例外處理
}
public class Exception_ {
?
public static void main(String[] args) {
String a = null;
try {
System.out.println(a.length());
System.out.println(a);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
注意事項
如果例外發生了,則例外發生那條陳述句后面的代碼不會執行,直接進入catch塊
如果例外沒有發生,正常執行try塊,不會進入catch塊
可以使用多個catch塊,捕獲不同的例外(進行不同的業務處理),要求父類例外在后面,子類例外在前面,例如: RuntimeException在后面,NullPointerException在前面,如果發生例外只會匹配一個catch,
try-catch-finally例外處理
相較于try-catch而言,多了一個finally塊,它的作用是:不管有沒有出現例外,都一定會執行finally塊中的代碼,
當然也可以使用try-finally,但這種方法和不處理例外是一樣的,最后會讓JVM機來處理例外,而JVM機處理例外的方式,就是直接輸出例外資訊然后終止程式,所以不建議這樣使用,
try-catch-finally案例
public class try_catch_finally{
public static void main(String args[]){
int[] a = {1,2,3};
try{
System.out.println(a[4]);
}catch{
System.out.println("陣列下標越界例外");
}finally{
System.out.println("finally塊執行....");
}
}
}
程式輸出:
陣列下標越界例外
finally塊執行....
練習題
考慮下面程式輸出:
package class_exception;
?
public class Test {
?
@SuppressWarnings("finally")
public static int method() {
try {
String[] names = new String[3];
if (names[1].equals("john")) {// 空指標例外
System.out.println(names[1]);
} else {
names[3] = "lucy";
}
return 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 2;
} catch (NullPointerException e) {
return 3;
} finally { // 一定要執行
return 4;
}
}
?
public static void main(String[] args) {
System.out.println(method());
}
}
?
練習題2
考慮程式輸出:
package class_exception;
?
public class Test {
?
public static int method() {
int i = 1;
try {
i++; // 2
String[] names = new String[3];
if (names[1].equals("john")) { // 空指標例外
System.out.println(names[1]);
} else {
names[3] = "lucy";
}
return 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 2;
} catch (NullPointerException e) {
return ++i; //提示:不是立即回傳 記錄 i= i+1 = 3 保存到 temp = 3
} finally {
++i;
System.out.println("i=" + i);
}
}
?
public static void main(String[] args) {
System.out.println(method());
}
}
應用案例
如果用戶輸入的不是一個正整數,就提示他反復輸入,直到輸入一個正整數為止
import java.util.Scanner;
?
public class ClassWork {
?
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int age;
System.out.println("輸入年齡:");
for(;;) {
try {
age = new Scanner(System.in).nextInt();
break;
} catch (Exception e) {
System.out.println("再次輸入年齡(正整數):");
continue;
}
}
System.out.println("END");
}
}
throws例外處理
如果一個方法(中的陳述句執行時)可能生成某種例外,但是并不能確定如何處理這種例外,則此方法應宣告拋出例外,表明該方法將不對這些例外進行處理,而由該方法的呼叫者負責處理,
在方法宣告中用throws陳述句可以宣告拋出例外的串列,throws后面的例外型別可以是方法中產生的例外型別,也可以是它的父類,
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Throws01 {
public static void main(String[] args) throws FileNotFoundException {
?
// 1. 使用try
// 2. 使用throws
m1();
System.out.println("ok");
}
public static void m1() throws FileNotFoundException {
FileInputStream fis = new FileInputStream("d://aa.txt");// 編譯例外
}
}
?
使用細節:
-
對于編譯例外,程式中必須處理,使用try-catch或throws
-
對于運行時例外,程式如果沒有處理,默認就是throws方式處理,將其拋給最頂層呼叫方JVM
-
子類重寫父類的方法時,對拋出例外的規定:子類重寫的方法,所拋出的例外型別要么和父類拋出的例外一致,要么為父類拋出的例外的型別的子型別
-
在throws 程序中,如果有方法 try-catch , 就相當于處理例外,就可以不必throws
細節3案例:
class Father {
public void m1() throws RuntimeException{
}
}
?
class Son extends Father{
@Override
public void m1() throws NullPointerException{
}
}
自定義例外
-
定義類:自定義例外類名(程式員自己寫) 繼承Exception或RuntimeException
-
如果繼承Exception,屬于編譯例外
-
如果繼承RuntimeException,屬于運行例外(一般來說,繼承RuntimeException)
自定義例外應用案例
package class_exception.ClassCustomException;
import java.util.Scanner;
?
/**
* 當我們接收Person物件年齡時,要求范圍在 1 – 130 之間,否則拋出一個自定義例外(要求 繼承自定義例外)
*/
public class ClassWork01 {
?
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Person p = new Person();
System.out.println("請輸入年齡:");
for(;;) {
try {
int a = scanner.nextInt();
p.setAge(a);
break;
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
System.out.println("請重新輸入年齡:");
continue;
}
}
}
}
?
class Person{
private int age;
?
public Person(int age) {
this.age = age;
}
public Person() {
}
?
//創建方法使用例外
public void setAge(int a) throws AException{
if(!(a>=0 && a<=130)) {
throw new AException("例外 要求范圍在 1 – 130 之間");
}
}
}
?
class AException extends RuntimeException{
/**
* 添加版本號,不用管
*/
private static final long serialVersionUID = 1L;
?
//使用構造器傳入例外資訊
public AException(String name){
super(name);
}
}
自定義例外應用案例2
package class_exception.ClassCustomException;
import java.util.Scanner;
/**
* 撰寫應用程式,接收一個數,要求不能輸入負數,進行例外處理,要求使用繼承 RuntimeException 來實作,
*/
public class ClassWork02 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("輸入一個數:");
try {
int a = s.nextInt();
//因為是運行時例外,也可以不使用try處理
if(a<0) {
throw new IntException("不能輸入負數");
}
}catch(RuntimeException e){
System.out.println("例外資訊:" + e.getMessage());
}
System.out.println("END");
}
}
?
class IntException extends RuntimeException{
private static final long serialVersionUID = 1L;
public IntException(String name) {
super(name);
}
}
throw 和 throws 的區別

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/236893.html
標籤:Java
上一篇:Goproxy.cn 核心代碼探究;https://github.com/goproxy/goproxy 開源模塊分析;
