繁体   English   中英

Java Try Catch块

[英]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 ,它也会捕获RuntimeExceptionError ):

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM