[英]Can I execute multiple catch blocks that correspond to one try block?
考慮我有一個包含3個語句的try塊,所有這些語句都會導致異常。 我希望所有3個例外都由它們相關的catch塊處理..是否可能?
像這樣的東西 - >
class multicatch
{
public static void main(String[] args)
{
int[] c={1};
String s="this is a false integer";
try
{
int x=5/args.length;
c[10]=12;
int y=Integer.parseInt(s);
}
catch(ArithmeticException ae)
{
System.out.println("Cannot divide a number by zero.");
}
catch(ArrayIndexOutOfBoundsException abe)
{
System.out.println("This array index is not accessible.");
}
catch(NumberFormatException nfe)
{
System.out.println("Cannot parse a non-integer string.");
}
}
}
是否有可能獲得以下輸出? - >>
Cannot divide a number by zero.
This array index is not accessible.
Cannot parse a non-integer string.
是否有可能獲得以下輸出?
不,因為只會拋出一個異常。 一旦拋出異常,執行就會離開try
塊,並且假設有一個匹配的catch
塊,它會繼續存在。 它不會返回到try
塊,因此您無法獲得第二個異常。
有關異常處理的一般課程,請參閱Java教程 ,有關詳細信息,請參閱JLS的第11.3節 。
如果要捕獲多個異常,則必須將代碼拆分為多個try / catch塊。
更好的方法是驗證數據和記錄錯誤,而不會觸發例外來執行此操作。
要添加到Jon的答案,雖然您不會從單個try
塊中捕獲多個異常,但您可以讓多個處理程序處理單個異常。
try
{
try
{
throw new Exception("This is an exception.");
}
catch(Exception foo)
{
System.Console.WriteLine(foo.Message);
throw; // rethrows foo for the next handler.
}
}
catch(Exception bar)
{
System.Console.WriteLine("And again: " + bar.Message);
}
這會產生輸出:
This is an exception.
And again: This is an exception.
這是一個REALY BAD PRACTICE,但你可以做下一個(使用finally
塊解決你的問題):
private static void Main()
{
int[] c={1};
String s="this is a false integer";
try
{
int z = 0;
int x = 5/z;
}
catch (ArithmeticException exception)
{
Console.WriteLine(exception.GetType().ToString());
}
finally
{
try
{
c[10] = 12;
}
catch(IndexOutOfRangeException exception)
{
Console.WriteLine(exception.GetType().ToString());
}
finally
{
try
{
int y = int.Parse(s);
}
catch (FormatException exception)
{
Console.WriteLine(exception.GetType().ToString());
}
}
Console.ReadKey();
}
}
一次顯示所有異常處理是不可能的。 每個異常catch
的目標是對每個Exception
類型進行不同的處理,否則將它們全部打印在一起是沒有意義的。
不,
它不會執行所有三個catch語句。 TRY塊檢查錯誤,然后執行從TRY塊中出來。 然后執行合適的捕獲。 在您的情況下, ArithmeticException位於異常層次結構的頂部。 因此它將執行,然后程序終止。
如果在ArithmeticException之前給出Catch(Exception e) ,那么將執行Exception catch ...更好地閱讀MSDN上的SystemException層次結構
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.