Java 每个异常都有一个必需的 try-catch 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29851253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does every exception have an required try-catch?
提问by Youri
A simple question and I can't find the answer for it. Is it required to every exception in Java to use a try-catch? Or is it only for the FileNotFoundException?
一个简单的问题,我找不到答案。Java 中的每个异常都需要使用 try-catch 吗?还是仅适用于 FileNotFoundException?
A lot of exceptions (IndexOutOfBoundException, ArithmeticException, IlligalArgumentException, NullPointerException) are saying that they didn't need an Exception, but FileNotFoundException does)... and I can't find the answer which do and which doesn't need try-catch.
很多异常(IndexOutOfBoundException、ArithmeticException、IlligalArgumentException、NullPointerException)都说他们不需要异常,但 FileNotFoundException 需要)......我找不到答案,哪些需要,哪些不需要 try-catch .
采纳答案by Aify
It's not absolutely required to have a try/catch
block for your exceptions. Instead, you can throw
them to someone who is able to handle the exception properly.
try/catch
为您的异常设置一个块并不是绝对必要的。相反,您可以将throw
它们交给能够正确处理异常的人。
There are 2 kinds of exceptions: Checked and Unchecked. A Checked exception can be consideredone that is found by the compiler, and the compiler knows that it has a chance to occur, so you need to catch
or throw
it. For example, opening a file. It has a chance to fail, and the compiler knows this, so you're forced to catch
or throw
the possible IOException
.
有两种异常:Checked 和 Unchecked。Checked 异常可以认为是编译器发现的异常,编译器知道它有机会发生,因此您需要catch
或throw
它。例如,打开一个文件。它有失败的机会,编译器知道这一点,所以你被迫catch
或throw
可能的IOException
.
An Unchecked exception can be consideredone that has a chance of occurring, but based on your code, the compiler doesn't know. In other words, it's a programming error. For example, if you're taking user input and expect a number, and the user enters something you didn't expect, such as a string, your program would throw a NumberFormatException
. You can predict these scenarios and put try/catch
to try and avoid them before they occur. Very rarely seen is a person adding a throws NullPointerException
or throws NumberFormatException
(or throwing any other Unchecked exception, for that matter). It's allowed, but explicitly creating that exception is weird and most people would say that it's bad coding style.
Unchecked 异常可以被认为是有可能发生的异常,但根据您的代码,编译器不知道。换句话说,这是一个编程错误。例如,如果您接受用户输入并期望输入一个数字,而用户输入了您不期望的内容(例如字符串),则您的程序将抛出一个NumberFormatException
. 您可以预测这些场景,try/catch
并在它们发生之前尝试避免它们。很少看到有人添加throws NullPointerException
或throws NumberFormatException
(或抛出任何其他未经检查的异常,就此而言)。这是允许的,但明确创建该异常很奇怪,大多数人会说这是糟糕的编码风格。
Note that all Checked suggestions mustbe caught or thrown to something that can handle it; if you don't do it, your program won't compile. If you throw it to something that can't handle it, then your program will likely crash if it occurs.
请注意,所有已检查的建议必须被捕获或扔给可以处理它的东西;如果你不这样做,你的程序将无法编译。如果你把它扔给不能处理它的东西,那么如果它发生,你的程序很可能会崩溃。
Also note that an unchecked Exception (eg: one that occurs during runtime, usually via bad user input or whatnot) will also usually crash your program. Thus, it's usually a good idea to use try/catch
when something can potentially go wrong, but you don't have to.
另请注意,未经检查的异常(例如:在运行时发生的异常,通常是由于用户输入错误或诸如此类)通常也会使您的程序崩溃。因此,try/catch
当某些事情可能出错时使用通常是个好主意,但您不必这样做。
Also interesting to note is that while Checked exceptions are subclasses of Exception and Unchecked exceptions are subclasses of RuntimeException, RuntimeException itself is a subclass of Exception. That means that if you really wanted to, a single try {} catch (Exception e) {}
will catch every single exception your program could possibly throw. Granted, this is considered a horrible way to deal with exceptions, and you should catch each one separately so that you can handle them separately. Please try not to use it.
还有一点值得注意的是,Checked 异常是 Exception 的子类,Unchecked 异常是 RuntimeException 的子类,而 RuntimeException 本身是 Exception 的子类。这意味着,如果您真的想要,singletry {} catch (Exception e) {}
将捕获您的程序可能抛出的每个异常。诚然,这被认为是一种处理异常的可怕方式,您应该单独捕获每个异常,以便您可以单独处理它们。请尽量不要使用它。
回答by Josh Edwards
No, not every exception requires a try-catch. Every checked exception requires a try catch. For example, a NullPointerException is an unchecked exception, so it does not require a try-catch, whereas a FileNotFoundException is checked, so it does require one. You can also add "throws" to the method signature and thus avoid needing a try-catch.
不,并非每个异常都需要 try-catch。每个已检查的异常都需要一个 try catch。例如,一个 NullPointerException 是一个未经检查的异常,所以它不需要 try-catch,而 FileNotFoundException 被检查,所以它确实需要一个。您还可以在方法签名中添加“throws”,从而避免需要 try-catch。
回答by user2248671
Only Checked exception explicit need to catch it, for other all kind of exception you can use "throws" to the method signature.
只有 Checked 异常显式需要捕获它,对于其他所有类型的异常,您可以对方法签名使用“抛出”。
回答by cbeutenmueller
Read: https://docs.oracle.com/javase/tutorial/essential/exceptions/
阅读:https: //docs.oracle.com/javase/tutorial/essential/exceptions/
Basically checked Exceptions need to be handled or thrown Unchecked Exceptions and Errors may be handled or thrown (although handling Error is in general considered bad practise).
基本上检查异常需要被处理或抛出未检查异常和错误可能被处理或抛出(尽管处理错误通常被认为是不好的做法)。
Checked exception is everything that inherits from java.lang.Exception
检查异常是从 java.lang.Exception 继承的所有内容
Unchecked exception is everything that inherits from java.lang.RuntimeException
未经检查的异常是从 java.lang.RuntimeException 继承的一切
Error is everything that inherits from java.lang.Error
错误是从 java.lang.Error 继承的一切
回答by J Atkin
Yes, but if you don't want to handle it in your method you can pass the exception to the caller of the method with the throws
keyword. Example:
是的,但是如果您不想在您的方法中处理它,您可以使用throws
关键字将异常传递给方法的调用者。例子:
void execption() throws Exception {
throw new Exception();
}
void caller() {
try {
execption();
} catch (Exception e) {
e.printStackTrace();
}
}
Edit: I'm a bit rusty on my java, like josh said you can have unchecked exceptions that don't need a try/catch like NullPointerException
, but you can add one if you think an unchecked exception may be thrown. Example:
编辑:我对我的 java 有点生疏,就像 josh 说你可以有不需要 try/catch 这样NullPointerException
的未经检查的异常,但是如果你认为可能会抛出未经检查的异常,你可以添加一个。例子:
Object obj = null;
obj.hashCode();// if you think a NPE will be thrown you can use a try/catch here
回答by Blip
When a method that you call explicitly throws an exception then you have to use try....catch
loop. But in case of the list you have given are all runtime exceptions. They get thrown when sometimes a program has inputs that were not expected or the program was put to some use that it was not intended for. These would not require a try....catch
loop.
当您显式调用的方法抛出异常时,您必须使用try....catch
循环。但是,如果您提供的列表都是运行时异常。当有时程序有意外的输入或程序被用于它不适合的某些用途时,它们就会被抛出。这些不需要try....catch
循环。