Java異常處置實例教程。本站提示廣大學習愛好者:(Java異常處置實例教程)文章只能為提供參考,不一定能成為您想要的結果。以下是Java異常處置實例教程正文
1、甚麼是異常?
起首,讓我們來看看下圖的例子:
在這個例子中,存在的毛病碼由除以0的成果。因為除以0而招致異常: ArithmeticException
HelloException.java
package com.yiibai.tutorial.exception;
public class HelloException {
public static void main(String[] args) {
System.out.println("Three");
// This division no problem.
int value = 10 / 2;
System.out.println("Two");
// This division no problem.
value = 10 / 1;
System.out.println("One");
// This division has problem, divided by 0.
// An error has occurred here.
value = 10 / 0;
// And the following code will not be executed.
System.out.println("Let's go!");
}
}
運轉這個例子,獲得的成果是:
可以看到掌握台屏幕上的告訴。毛病告訴是很清晰的,包含代碼行的信息。
讓我們經由過程下圖中的流程看看上面的法式:
我們將修正上述實行例的代碼。
HelloCatchException.java
package com.yiibai.tutorial.exception;
public class HelloCatchException {
public static void main(String[] args) {
System.out.println("Three");
// This division no problem.
int value = 10 / 2;
System.out.println("Two");
// This division no problem.
value = 10 / 1;
System.out.println("One");
try {
// This division has problem, divided by 0.
// An error has occurred here.
value = 10 / 0;
// And the following code will not be executed.
System.out.println("Value =" + value);
} catch (ArithmeticException e) {
// The code in the catch block will be executed
System.out.println("Error: " + e.getMessage());
// The code in the catch block will be executed
System.out.println("Ignore...");
}
// This code is executed
System.out.println("Let's go!");
}
}
運轉示例成果:
Three
Two
One
Error: / by zero
Ignore...
Let's go!
我們將按以下實例圖象的流程來說明上面的法式。
2、 異常條理構造
這是Java異常的分層圖的模子。
最高的類是:Throwable
兩個直接子類是 Error 和 Exception。
在異常轉移有一個RuntimeException子類,包含Java中的編譯時未檢討異常。檢討並撤消檢討在編譯時,鄙人一部門的實行示例中解釋。
留意:您的類應當從兩個分支:Error或Exception繼續,而不是直接從Throwable繼續。
當一個靜態鏈接掉敗,或在虛擬機的一些其他的“硬”毛病產生時,虛擬機激發這個毛病。典范的Java法式不捕捉毛病,所以Java法式都不會拋出任何毛病。年夜多半法式拋出並捕捉從Exception類派生的對象。異常指導湧現了一個成績,然則這些成績其實不是嚴重體系性成績。你寫的年夜多半法式將會拋出和捕捉異常。
Exception類在Java包界說了很多子類。這些子類指明分歧類型的能夠會產生異常。 例如,NegativeArraySizeException注解法式試圖創立一個年夜小為負的數組。
一個導演的子類在Java說話中的特別寄義: RuntimeException類表現Java虛擬機中產生(在運轉時代)的異常。運轉時異常的一個例子是NullYiibaierException異常,個中,當一種辦法試圖經由過程一個空援用來拜訪對象的成員時就會激發。 NullYiibaierException 可以在任何處所湧現某個法式試圖撤消援用一個對象的援用。常常檢討異常捕捉的利益遠遠跨越它的本錢。
因為運轉時異常是無所不在的,在試圖捕捉或指定一切的時光是白費的作法(弗成讀和弗成保護的代碼), 編譯器許可運轉時異常去未捕捉和指定。
Java包界說幾個RuntimeException類。您可以捕捉這些異常,就像其他異常。然則其實不須要一種辦法來指定它拋出運轉時異常。另外可以創立本身的RuntimeException子類。 運轉時異常 - 上面評論辯論包括什麼時候和若何應用運轉時異常停止了深刻商量。 3、應用try-catch處置異常
編寫從Exception 繼續的類。
AgeException.java
package com.yiibai.tutorial.exception.basic;
public class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}
TooYoungException.java
package com.yiibai.tutorial.exception.basic;
public class TooYoungException extends AgeException {
public TooYoungException(String message) {
super(message);
}
}
TooOldException.java
package com.yiibai.tutorial.exception.basic;
public class TooOldException extends AgeException {
public TooOldException(String message) {
super(message);
}
}
和AgeUtils類檢討年紀的檢討靜態辦法。
AgeUtils.java
package com.yiibai.tutorial.exception.basic;
public class AgeUtils {
// This method checks the age.
// If age is less than 18, the method will throw an exception TooYoungException
// If age greater than 40, the method will throw an exception TooOldException
public static void checkAge(int age) throws TooYoungException,
TooOldException {
if (age < 18) {
// If age is less than 18, an exception will be thrown
// This method ends here.
throw new TooYoungException("Age " + age + " too young");
} else if (age > 40) {
// If age greater than 40, an exception will be thrown.
// This method ends here.
throw new TooOldException("Age " + age + " too old");
}
// If age is between 18-40.
// This code will be execute.
System.out.println("Age " + age + " OK!");
}
}
檢討異常和未經檢討的異常:
AgeException是Exception,TooOldException的子類和TooYoungException2是 AgeException直接子類,所以它們是“Checked Exception”
在AgeUtils.checkAge(int)辦法曾經拋出異常,須要經由過程症結字“throws”,列出它們的辦法聲明。或許可以聲明拋出更多的級別。
在應用 AgeUtils.checkAge(int) 地位也必需停止處置,以捕捉異常,或持續拋出去。
"Checked exception" 是由 "Java Compiler"來檢討。
有兩個選擇:
TryCatchDemo1.java
package com.yiibai.tutorial.exception.basic;
public class TryCatchDemo1 {
public static void main(String[] args) {
System.out.println("Start Recruiting ...");
// Check age
System.out.println("Check your Age");
int age = 50;
try {
AgeUtils.checkAge(age);
System.out.println("You pass!");
} catch (TooYoungException e) {
// Do something here ..
System.out.println("You are too young, not pass!");
System.out.println(e.getMessage());
} catch (TooOldException e) {
// Do something here ..
System.out.println("You are too old, not pass!");
System.out.println(e.getMessage());
}
}
}
鄙人面的例子中,我們將經由過程父類捕捉異常(超Exception類)。
TryCatchDemo2.java
package com.yiibai.tutorial.exception.basic;
public class TryCatchDemo2 {
public static void main(String[] args) {
System.out.println("Start Recruiting ...");
// Check age
System.out.println("Check your Age");
int age = 15;
try {
// Here can throw TooOldException or TooYoungException
AgeUtils.checkAge(age);
System.out.println("You pass!");
} catch (AgeException e) {
// If an exception occurs, type of AgeException
// This catch block will be execute
System.out.println("Your age invalid, you not pass");
System.out.println(e.getMessage());
}
}
}
也能夠組分歧的異常在塊中來處置,假如它們對邏輯法式處置是雷同的方法。
TryCatchDemo3.java
package com.yiibai.tutorial.exception.basic;
public class TryCatchDemo3 {
public static void main(String[] args) {
System.out.println("Start Recruiting ...");
// Check age
System.out.println("Check your Age");
int age = 15;
try {
// Here can throw TooOldException or TooYoungException
AgeUtils.checkAge(age);
System.out.println("You pass!");
} catch (TooYoungException | TooOldException e) {
// Catch multi exceptions in one block.
System.out.println("Your age invalid, you not pass");
System.out.println(e.getMessage());
}
}
}
4、 try-catch-finally
我們已習氣於經由過程 try-catch 塊捕捉毛病。Try-catch-finally 來完整處置異常。
try {
// Do something here
} catch (Exception1 e) {
// Do something here
} catch (Exception2 e) {
// Do something here
} finally {
// Finally block is always executed
// Do something here
}
TryCatchFinallyDemo.java
package com.yiibai.tutorial.exception.basic;
public class TryCatchFinallyDemo {
public static void main(String[] args) {
String text = "001234A2";
int value = toInteger(text);
System.out.println("Value= " + value);
}
public static int toInteger(String text) {
try {
System.out.println("Begin parse text: " + text);
// An Exception can throw here (NumberFormatException).
int value = Integer.parseInt(text);
return value;
} catch (NumberFormatException e) {
// In the case of 'text' is not a number.
// This catch block will be executed.
System.out.println("Number format exception " + e.getMessage());
// Returns 0 if NumberFormatException occurs
return 0;
} finally {
System.out.println("End parse text: " + text);
}
}
}
這是法式的流程。 finally塊不管甚麼情形下總會被履行。
5、 圍繞異常
Person.java
package com.yiibai.tutorial.exception.wrap;
public class Person {
public static final String MALE = "male";
public static final String FEMALE = "female";
private String name;
private String gender;
private int age;
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
GenderException.java
package com.yiibai.tutorial.exception.wrap;
// Gender Exception.
public class GenderException extends Exception {
public GenderException(String message) {
super(message);
}
}
ValidateException 類包有其他異常。
ValidateException.java
package com.yiibai.tutorial.exception.wrap;
public class ValidateException extends Exception {
// Wrap an Exception
public ValidateException(Exception e) {
super(e);
}
}
ValidateUtils.java
package com.yiibai.tutorial.exception.wrap;
import com.yiibai.tutorial.exception.basic.AgeUtils;
public class ValidateUtils {
public static void checkPerson(Person person) throws ValidateException {
try {
// Check age.
// Valid if between 18-40
// This method can throw TooOldException, TooYoungException.
AgeUtils.checkAge(person.getAge());
} catch (Exception e) {
// If not valid
// Wrap this exception by ValidateException, and throw
throw new ValidateException(e);
}
// If that person is Female, ie invalid.
if (person.getGender().equals(Person.FEMALE)) {
GenderException e = new GenderException("Do not accept women");
throw new ValidateException(e);
}
}
}
WrapperExceptionDemo.java
package com.yiibai.tutorial.exception.wrap;
public class WrapperExceptionDemo {
public static void main(String[] args) {
// One participant recruitment.
Person person = new Person("Marry", Person.FEMALE, 20);
try {
// Exceptions may occur here.
ValidateUtils.checkPerson(person);
} catch (ValidateException wrap) {
// Get the real cause.
// May be TooYoungException, TooOldException, GenderException
Exception cause = (Exception) wrap.getCause();
if (cause != null) {
System.out.println("Not pass, cause: " + cause.getMessage());
} else {
System.out.println(wrap.getMessage());
}
}
}
}
6、RuntimeException和子類 RuntimeException類及其子類都是“未檢討的破例”。它不是由Java編譯器在編譯時停止檢討。在某些情形下,你可以從這個分支繼續編寫本身的異常。
上面是屬於RuntimeException分支一些類(固然,這還不是全體)。
一些處置這類類型異常的例子:
6.1- NullYiibaierException
這是最多見的異常,平日會招致毛病在法式中。異常被拋出,當你挪用辦法或拜訪一個空對象的字段。
NullYiibaierExceptionDemo.java
package com.yiibai.tutorial.exception.runtime;
public class NullYiibaierExceptionDemo {
// For example, here is a method that can return null string.
public static String getString() {
if (1 == 2) {
return "1==2 !!";
}
return null;
}
public static void main(String[] args) {
// This is an object that references not null.
String text1 = "Hello exception";
// Call the method retrieves the string length.
int length = text1.length();
System.out.println("Length text1 = " + length);
// This is an object that references null.
String text2 = getString();
// Call the method retrieves the string length.
// NullYiibaierException will occur here.
// It is an exception occurs at runtime (type of RuntimeException)
// Javac compiler does not force you to use a try-catch block to handle it
length = text2.length();
System.out.println("Finish!");
}
}
運轉示例的成果:
在實際中,像處置其他異常時,可使用 try-catch 來捕捉並處置這個異常。 但是,這是機械的,平日情形下,我們應當檢討,以確保在應用它之前,對象不為空值。
您可以更正下面的代碼,使其相似於上面的以免空指針異常:
// This is a null object.
String text2 = getString();
// Check to make sure 'Text2' are not null.
// Instead of using try-catch.
if (text2 != null) {
length = text2.length();
}
6.2- ArrayIndexOfBoundException
當您試圖拜訪一個有效的索引的數組元素就會產生此異常。例如,一個數組有10個元素可以拜訪,但您拜訪的是索引為20的元素。
ArrayIndexOfBoundsExceptionDemo.java
package com.yiibai.tutorial.exception.runtime;
public class ArrayIndexOfBoundsExceptionDemo {
public static void main(String[] args) {
String[] strs = new String[] { "One", "Two", "Three" };
// Access to the element has index 0.
String str1 = strs[0];
System.out.println("String at 0 = " + str1);
// Access to the element has index 5.
// ArrayIndexOfBoundsException occur here.
String str2 = strs[5];
System.out.println("String at 5 = " + str2);
}
}
為了不 ArrayIndexOfBoundsException,我們更多的應當是檢討數組而不是應用try-catch。
if (strs.length > 5) {
String str2 = strs[5];
System.out.println("String at 5 = " + str2);
} else {
System.out.println("No elements with index 5");
}
以上就是本文的全體內容,願望對年夜家的進修有所贊助。