简体   繁体   English

Java Try Catch块

[英]Java Try Catch block

I initially started programming in college and learnt vb.net. 我最初开始在大学编程并学习vb.net。 Now I have decided to make the move to Java and have some queries. 现在我决定转向Java并进行一些查询。 In vb, the try catch statement is laid out as follows 在vb中,try catch语句的布局如下

try
Catch ex as exception
finally
End catch

but from the java website ( https://docs.oracle.com/javase/tutorial/essential/exceptions/putItTogether.html ) i found that in java you use two catches like so: 但是从java网站( https://docs.oracle.com/javase/tutorial/essential/exceptions/putItTogether.html )我发现在java中你使用两个类似的捕获:

    try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

i was hoping someone could explain why you need two catches in java and what do the respective catches do/catch. 我希望有人可以解释为什么你需要在Java中捕获两次,以及各自捕获的捕获量是多少。

Thanks. 谢谢。

In Java, you can use multiple catch blocks. 在Java中,您可以使用多个catch块。

It doesn't necessarily means you have to. 它并不一定意味着你必须这样做。

It depends on the code your have in the try block, and how many checked Exception s it may potentially throw (or even unchecked Exception s if you really want to catch that, typically you don't and you don't have to ). 这取决于你必须在代码try块,并检查了多少Exception的IT可能会潜在地抛出(甚至是未经检查的Exception ■如果你真的想赶上那班,通常你不这样做,你也不必 )。

One bad practice is to use a single handler for general Exception (or worse, Throwable , which would also catch RuntimeException s and Error s): 一个不好的做法是使用单个处理程序进行常规Exception (或者更糟糕的是, Throwable ,它也会捕获RuntimeExceptionError ):

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

The good practice is to catch all potentially thrown checked Exception s. 好的做法是捕获所有可能抛出的已检查的 Exception

If some of them are related in terms of inheritance, always catch the child classes first (ie the more specific Exception s), lest your code won't compile: 如果它们中的一些在继承方面是相关的,那么总是首先捕获子类(即更具体的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
}

Also take a look at Java 7's multi-catch blocks , where unrelated Exception s can be caught all at once with a | 另请参阅Java 7的多捕获块 ,其中可以使用|一次性捕获不相关的Exception separator between each Exception type: 每个Exception类型之间的分隔符:

try (optionally with resources) {
    // stuff that throws FileNotFoundException and MyOwnCheckedException
}
// below exceptions are unrelated
catch (FileNotFoundException | MyOwnCheckedException e) {
    // TODO
}

Note 注意

In this example you linked to, the first code snippet below Putting it all together may arguably be considered as sub-optimal: it does catch the potentially thrown Exception s, but one of them is an IndexOutOfBoundsException , which is a RuntimeException (unchecked) and should not be handled in theory. 在你链接的这个例子中,下面的第一个代码片段将它放在一起可能被认为是次优的:它确实捕获了可能抛出的Exception ,但其中一个是一个IndexOutOfBoundsException ,它是一个RuntimeException (未经检查)和不应该在理论上处理。

Instead, the SIZE variable (or likely constant) should be replaced by a reference to the size of the List being iterated, ie list.size() , in order to prevent IndexOutOfBoundsException from being thrown. 相反, SIZE变量(或可能是常量)应该被对迭代的List的大小的引用list.size()list.size()替换,以防止抛出IndexOutOfBoundsException

I guess in this case it's just to provide an example though. 我想在这种情况下,它只是提供一个例子。

The code that is on the page that is in link i have modified it with single exception. 链接i中页面上的代码已修改它,但有一个例外。 Problem here is that in this case you will not able to know that exception is where whether due to 这里的问题是,在这种情况下,您将无法知道异常是否由于

IndexOutOfBoundsException or IOException IndexOutOfBoundsException或IOException

just you know that a exception occurs 只是你知道发生了异常

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");
            }
        }
    }
}

Let us understand the concept it is better to know why the code fails due to which particular type of exception whether 让我们理解这个概念,更好地了解代码为什么会因为特定类型的异常而失败

IndexOutOfBoundsException or IOException IndexOutOfBoundsException或IOException

Now The Code with handling of different 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<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");
            }
        }
    }
}

Here we could come to know that whether it fails due to creation of file at location 在这里,我们可以知道它是否由于在位置创建文件而失败

e://OutFile.txt drive Not on my system e://OutFile.txt驱动器不在我的系统上

error printed as 错误打印为

Caught Exception: e:\\OutFile.txt (The system cannot find the path specified) Entering try statement PrintWriter not open 抓到异常:e:\\ OutFile.txt(系统找不到指定的路径)输入try语句PrintWriter未打开

Next Case 下一个案例

Now when i comment the line 现在,当我评论这条线

list.add(new Integer(i)); 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");
                }
            }
        }
    }

then it clearly says that it fails for index out of bound exception 然后它清楚地说它没有索引超出约束的异常

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

So for the purpose of debugging the application properly and efficiently it is good. 因此,为了正确有效地调试应用程序,这是好事。

I have created condition for the other type of 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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