[英]Java Try Catch block
我最初開始在大學編程並學習vb.net。 現在我決定轉向Java並進行一些查詢。 在vb中,try catch語句的布局如下
try
Catch ex as exception
finally
End catch
但是從java網站( https://docs.oracle.com/javase/tutorial/essential/exceptions/putItTogether.html )我發現在java中你使用兩個類似的捕獲:
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
我希望有人可以解釋為什么你需要在Java中捕獲兩次,以及各自捕獲的捕獲量是多少。
謝謝。
在Java中,您可以使用多個catch
塊。
它並不一定意味着你必須這樣做。
這取決於你必須在代碼try
塊,並檢查了多少Exception
的IT可能會潛在地拋出(甚至是未經檢查的Exception
■如果你真的想趕上那班,通常你不這樣做,你也不必 )。
一個不好的做法是使用單個處理程序進行常規Exception
(或者更糟糕的是, Throwable
,它也會捕獲RuntimeException
和Error
):
try {
// stuff that throws multiple exceptions
}
// bad
catch (Exception e) {
// TODO
}
好的做法是捕獲所有可能拋出的已檢查的 Exception
。
如果它們中的一些在繼承方面是相關的,那么總是首先捕獲子類(即更具體的Exception
),以免代碼無法編譯:
try {
// stuff that throws FileNotFoundException AND IOException
}
// good: FileNotFoundException is a child class of IOException - both checked
catch (FileNotFoundException fnfe) {
// TODO
}
catch (IOException ioe) {
// TODO
}
另請參閱Java 7的多捕獲塊 ,其中可以使用|
一次性捕獲不相關的Exception
每個Exception
類型之間的分隔符:
try (optionally with resources) {
// stuff that throws FileNotFoundException and MyOwnCheckedException
}
// below exceptions are unrelated
catch (FileNotFoundException | MyOwnCheckedException e) {
// TODO
}
注意
在你鏈接的這個例子中,下面的第一個代碼片段將它放在一起可能被認為是次優的:它確實捕獲了可能拋出的Exception
,但其中一個是一個IndexOutOfBoundsException
,它是一個RuntimeException
(未經檢查)和不應該在理論上處理。
相反, SIZE
變量(或可能是常量)應該被對迭代的List
的大小的引用list.size()
即list.size()
替換,以防止拋出IndexOutOfBoundsException
。
我想在這種情況下,它只是提供一個例子。
鏈接i中頁面上的代碼已修改它,但有一個例外。 這里的問題是,在這種情況下,您將無法知道異常是否由於
IndexOutOfBoundsException或IOException
只是你知道發生了異常
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class ListOfNumbers {
public static void main(String... s) {
ListOfNumbers lon = new ListOfNumbers();
lon.writeList();
}
private List<Integer> list;
private static final int SIZE = 10;
public ListOfNumbers() {
list = new ArrayList<Integer>(SIZE);
for (int i = 0; i < SIZE; i++) {
list.add(new Integer(i));
}
}
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering" + " try statement");
out = new PrintWriter(new FileWriter("e://OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
} catch (Exception e) {
System.err.println("Caught Exception: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
}
讓我們理解這個概念,更好地了解代碼為什么會因為特定類型的異常而失敗
IndexOutOfBoundsException或IOException
現在代碼處理不同的異常
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class ListOfNumbers {
public static void main(String... s) {
ListOfNumbers lon = new ListOfNumbers();
lon.writeList();
}
private List<Integer> list;
private static final int SIZE = 10;
public ListOfNumbers() {
list = new ArrayList<Integer>(SIZE);
for (int i = 0; i < SIZE; i++) {
list.add(new Integer(i));
}
}
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering" + " try statement");
out = new PrintWriter(new FileWriter("e://OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
} catch (IndexOutOfBoundsException e) {
System.err.println("Caught IndexOutOfBoundsException: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
}
在這里,我們可以知道它是否由於在位置創建文件而失敗
e://OutFile.txt驅動器不在我的系統上
錯誤打印為
抓到異常:e:\\ OutFile.txt(系統找不到指定的路徑)輸入try語句PrintWriter未打開
下一個案例
現在,當我評論這條線
list.add(new Integer(i));
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class ListOfNumbers {
public static void main(String... s) {
ListOfNumbers lon = new ListOfNumbers();
lon.writeList();
}
private List<Integer> list;
private static final int SIZE = 10;
public ListOfNumbers() {
list = new ArrayList<Integer>(SIZE);
for (int i = 0; i < SIZE; i++) {
// list.add(new Integer(i));
}
}
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering" + " try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
} catch (IndexOutOfBoundsException e) {
System.err.println("Caught IndexOutOfBoundsException: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
}
然后它清楚地說它沒有索引超出約束的異常
輸入try語句Caught IndexOutOfBoundsException:Index:0,Size:0關閉PrintWriter
因此,為了正確有效地調試應用程序,這是好事。
我為其他類型的異常創建了條件
NoClassDefFoundError
java.lang.NoClassDefFoundError: ListOfNumbers
Caused by: java.lang.ClassNotFoundException: stackprac.ListOfNumbers
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Exception in thread "main" Process exited with exit code 1.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.