JAVA中異常處理機制:
JAVA語言提供兩種異常處理機制:捕獲異常和聲明拋棄異常
1)捕獲異常:在Java程序運行過程中系統得到一個異常對象是,它將會沿着方法的調用棧逐層回溯,尋找處理這一異常的代碼。找到能夠處理這種類型異常的方法后,運行時系統把當前異常交給這個方法處理;如果找不到可以捕獲異常的方法,則運行時系統將終止,相應的Java程序也將退出。
2)聲明拋棄異常:當Java程序運行時系統得到一個異常對象時,如果一個方法並不知道如何處理所出現的異常,則可在方法聲明時,聲明拋棄異常。聲明拋棄異常是在一個方法聲明中的throws子句中指明的。
下面將通過若干個例子說明JAVA中異常處理機制
一:AboutException.java
源代碼:
import javax.swing.*;
class AboutException {
public static void main(String[] a)
{
double i=1, j=0, k;
k=i/j;
try
{
k = i/j; // Causes division-by-zero exception
//throw new Exception("Hello.Exception!");
}
catch ( ArithmeticException e)
{
System.out.println("被0除. "+ e.getMessage());
}
catch (Exception e)
{
if (e instanceof ArithmeticException)
System.out.println("被0除");
else
{
System.out.println(e.getMessage());
}
}
finally
{
JOptionPane.showConfirmDialog(null,"OK");
System.out.println(+k);
}
}
}
結果截圖:


分析:
程序中,當i,j的數據類型改為整型的話,程序會拋出Exception的錯誤,導致程序無法正常運行,如果把i,j改為double類型是,程序輸出無窮大這一結果;
JAVA異常處理機制:
把可能會發生錯誤的代碼放進try語句塊中。
當程序檢測到出現了一個錯誤時會拋出一個異常對象。異常處理代碼會捕獲並處理這個錯誤。
catch語句塊中的代碼用於處理錯誤。
當異常發生時,程序控制流程由try語句塊跳轉到catch語句塊。
不管是否有異常發生,finally語句塊中的語句始終保證被執行。
如果沒有提供合適的異常處理代碼,JVM將會結束掉整個應用程序。
二:CatchWho.java
源代碼:
public class CatchWho {
public static void main(String[] args) {
try {
try {
throw new ArrayIndexOutOfBoundsException();
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/內層try-catch");
}
throw new ArithmeticException();
}
catch(ArithmeticException e) {
System.out.println("發生ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/外層try-catch");
}
}
}
運行結果:

三:CatchWho2.java
源代碼:
public class CatchWho2 {
public static void main(String[] args) {
try {
try {
throw new ArrayIndexOutOfBoundsException();
}
catch(ArithmeticException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/內層try-catch");
}
throw new ArithmeticException();
}
catch(ArithmeticException e) {
System.out.println("發生ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println( "ArrayIndexOutOfBoundsException" + "/外層try-catch");
}
}
}
運行結果:
四:EmbedFinally.java
源代碼:
public class EmbededFinally {
public static void main(String args[]) {
int result;
try {
System.out.println("in Level 1");
try {
System.out.println("in Level 2");
// result=100/0; //Level 2
try {
System.out.println("in Level 3");
result=100/0; //Level 3
}
catch (Exception e) {
System.out.println("Level 3:" + e.getClass().toString());
}
finally {
System.out.println("In Level 3 finally");
}
// result=100/0; //Level 2
}
catch (Exception e) {
System.out.println("Level 2:" + e.getClass().toString());
}
finally {
System.out.println("In Level 2 finally");
}
// result = 100 / 0; //level 1
}
catch (Exception e) {
System.out.println("Level 1:" + e.getClass().toString());
}
finally {
. System.out.println("In Level 1 finally");
}
}
}
運行結果:程序無法運行!
分析:源代碼中69行出多了一個“.”,若將其刪除,會有如下的運行結果:
五:finally語句一定會執行嗎?
源代碼:
public class SystemExitAndFinally {
public static void main(String[] args)
{
try{
System.out.println("in main");
throw new Exception("Exception is thrown in main");
//System.exit(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
System.exit(0);
}
finally
{
System.out.println("in finally");
}
}
}
運行截圖:
分析:
當有多層嵌套的finally時,異常在不同的層次拋出 ,在不同的位置拋出,可能會導致不同的finally語句塊執行順序
六:如何跟蹤異常的傳播路徑?
源代碼:
// UsingExceptions.java
// Demonstrating the getMessage and printStackTrace
// methods inherited into all exception classes.
public class PrintExceptionStack {
public static void main( String args[] )
{
try {
method1();
}
catch ( Exception e ) {
System.err.println( e.getMessage() + "\n" );
e.printStackTrace();
}
}
public static void method1() throws Exception
{
method2();
}
public static void method2() throws Exception
{
method3();
}
public static void method3() throws Exception
{
throw new Exception( "Exception thrown in method3" );
}
}
運行截圖:
分析:
當程序中出現異常時,JVM會依據方法調用順序依次查找有關的錯誤處理程序。
可使用printStackTrace 和 getMessage方法了解異常發生的情況:
printStackTrace:打印方法調用堆棧。
每個Throwable類的對象都有一個getMessage方法,它返回一個字串,這個字串是在Exception構造函數中傳入的,通常讓這一字串包含特定異常的相關信息。
七:設計型程序(根據輸入的=成績,判斷該門功課的水平“包括異常處理機制,及不管用戶輸入什么內容,都不會崩潰”)
源代碼:
package tichangchuli;
import java.util.Scanner;
@SuppressWarnings("serial")
class ChenjiException extends Exception{
public ChenjiException(String s)
{
super(s);
}
}
public class chengji {
public static boolean Test(String ss){
boolean flag=true;
char []chArr=ss.toCharArray();
int l=ss.length();
for(int i=0;i<l;i++){
if(chArr[i]<48||chArr[i]>57)
{flag=false;}
}
return flag;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner in=new Scanner(System.in);
System.out.println("請輸入學生成績");
try{
String u=in.next();
if(Test(u))
{
int chengj=Integer.parseInt(u);
if(chengj>=90)
{
System.out.println("優");
}
else if(chengj<90&&chengj>=80)
{
System.out.println("良");
}
else if(chengj<80&&chengj>=70)
{
System.out.println("中");
}
else if(chengj<70&&chengj>=60)
{
System.out.println("及格");
}
else
{
System.out.println("不及格");
}
}
else
throw new ChenjiException("輸入格式不正確!");
}
catch(ChenjiException e)
{
System.out.println(e);
}
}
}
結果截圖:



