1 java runtime-error exception
我知道错误 [运行时错误]和异常之间的区别.{ 在谈到JAVA时说话 }.但是致命错误和异常是相同的事情还是它们是不同的.或者java中没有致命错误的概念?我搜索谷歌,但它很混乱.
简而言之,您可以使用这个小指南.请参阅每个类别中带有Java异常层次结构(红色)和几个示例(蓝色)的类图.
Throwable:使用Java异常机制抛出(和捕获)的任何东西的共同祖先.
Error:你可能会想到Error你所谓的"致命异常".即使尝试恢复应用程序通常也没有意义.OutOfMemoryError或者StackOverflowError是这样的致命错误,你几乎不能做任何事情中的应用.
不要抓住Errors,让程序崩溃并解决外面的问题.
RuntimeException:应该主要用于程序员的错误(参见下面的例子),例如未处理的空指针de-reference,不满足方法契约等.
虽然它们是将所有异常包装到RuntimeExceptions中并在业务代码之外处理的技术(通常使用AOP),但通常会出现一种RuntimeException意味着您应该让程序崩溃并修复其源代码的方法.
/**
* Does something with s.
* @param s The input string
*/
public void badlyDesignedMethod(String s) {
// Here the programmer omitted to check s against null
int i = s.length();
...
}
/**
* Does something with s.
* @param s The input string; must not be null
*/
public void betterDesignedMethod(String s) {
if (s == null) {
throw new IllegalArgumentException("The parameter s must not be null!);
}
int i = s.length();
...
}
public void caller() {
badlyDesignedMethod(null); // will throw NullPointerException
// It is the fault of the programmer of badlyDesignedMethod()
// as they have not specified that the parameter must not be null.
betterDesignedMethod(null); // will throw IllegalArgumentException
// Now it is the fault of the programmer of caller()
// as they violated the contract of betterDesignedMethod()
// which DOES tell them that the parameter must not be null
}
Run Code Online (Sandbox Code Playgroud)
无论是ErrorS和RuntimeExceptions为未选中,这意味着一个方法不必声明它抛出他们的来电者没有抓住他们,即不具备环绕与呼叫try-catch块.
其他异常(继承自Exception而不是来自RuntimeException):应声明(throws...)和 catch(try-catch)的异常,这些异常主要是从方法向其调用者传递有用信息:数据库不可用,文件无法打开等.
这些异常是由您的代码处理的.与作为"意外异常"的运行时异常相比,它们是"预期异常".
public void doSomethingWithFile(String fileName) throws IOException {
if (/* file is not accessible */) {
throw new IOException("File " + fileName + " is not accessible!");
}
...
}
public void caller() {
try {
doSomethingWithFile("/home/honza/file.txt");
}
catch (IOException e) {
// handle the fact that the file is not accessible
return;
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4880 次 |
| 最近记录: |