Java Try Catch块

我最初开始在大学编程并学习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 (如果你真的想要捕获它,甚至是未经检查的Exception ,通常你没有,你不需要)。

一个不好的做法是使用单个处理程序进行常规Exception (或者更糟糕的是, Throwable ,它也会捕获RuntimeExceptionError ):

 try { // stuff that throws multiple exceptions } // bad catch (Exception e) { // TODO } 

好的做法是捕获所有可能被抛出的已检查的 Exception

如果其中一些在inheritance方面是相关的,那么总是首先捕获子类(即更具体的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() ,以防止抛出IndexOutOfBoundsException

我想在这种情况下,它只是提供一个例子。

链接i中页面上的代码已修改它,但有一个例外。 这里的问题是,在这种情况下,您将无法知道exception是否由于

IndexOutOfBoundsException或IOException

只是你知道发生了exception

 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 list; private static final int SIZE = 10; public ListOfNumbers() { list = new ArrayList(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"); } } } } 

让我们理解这个概念,更好地了解代码为什么会因为哪种特定类型的exception而失败

IndexOutOfBoundsException或IOException

现在代码处理不同的exception

 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 list; private static final int SIZE = 10; public ListOfNumbers() { list = new ArrayList(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驱动器不在我的系统上

错误打印为

抓到exception: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 list; private static final int SIZE = 10; public ListOfNumbers() { list = new ArrayList(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"); } } } } 

然后它清楚地表明它失败了索引超出限制的exception

输入try语句Caught IndexOutOfBoundsException:Index:0,Size:0关闭PrintWriter

因此,为了正确有效地调试应用程序,这是好事。

我为其他类型的exception创建了条件

 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.