Joh*_*nna 96 java exception-handling exception file
在Java中,有没有办法获取(catch)all exceptions而不是单独捕获异常?
jjn*_*guy 105
如果需要,可以向方法添加throws子句.然后,您不必立即捕获已检查的方法.这样,你可以赶上exceptions后来(也许与其他同时exceptions).
代码如下:
public void someMethode() throws SomeCheckedException {
// code
}
Run Code Online (Sandbox Code Playgroud)
然后你可以处理exceptions如果你不想在那个方法中处理它们.
为了捕获所有异常,可能会抛出一些代码块:(这也会抓住Exceptions你自己写的)
try {
// exceptional block of code ...
// ...
} catch (Exception e){
// Deal with e as you please.
//e may be any type of exception at all.
}
Run Code Online (Sandbox Code Playgroud)
有效的原因是因为Exception是所有异常的基类.因此,可能抛出的任何异常都是Exception(大写'E').
如果要处理自己的异常,首先只需catch在通用异常之前添加一个块.
try{
}catch(MyOwnException me){
}catch(Exception e){
}
Run Code Online (Sandbox Code Playgroud)
cod*_*lhu 92
虽然我同意捕获原始异常并不是一种好的方式,但是有一些方法可以处理异常,这些异常提供了卓越的日志记录以及处理意外情况的能力.由于您处于异常状态,因此您可能对获取良好信息比对响应时间更感兴趣,因此性能的实例不应该是一个大问题.
try{
// IO code
} catch (Exception e){
if(e instanceof IOException){
// handle this exception type
} else if (e instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
throw e;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这并没有考虑到IO也可以抛出错误的事实.错误不是例外.错误是与异常不同的继承层次结构,尽管它们共享基类Throwable.由于IO可以抛出错误,你可能想要抓住Throwable
try{
// IO code
} catch (Throwable t){
if(t instanceof Exception){
if(t instanceof IOException){
// handle this exception type
} else if (t instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else if (t instanceof Error){
if(t instanceof IOError){
// handle this Error
} else if (t instanceof AnotherError){
//handle different Error
} else {
// We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else {
// This should never be reached, unless you have subclassed Throwable for your own purposes.
throw t;
}
}
Run Code Online (Sandbox Code Playgroud)
All*_*lan 14
捕获基本异常'Exception'
try {
//some code
} catch (Exception e) {
//catches exception and all subclasses
}
Run Code Online (Sandbox Code Playgroud)
您的意思是捕获抛出的Exception任何类型,而不是仅捕获特定的异常吗?
如果是这样:
try {
//...file IO...
} catch(Exception e) {
//...do stuff with e, such as check its type or log it...
}
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以在单个 catch 块中捕获多个异常。
try{
// somecode throwing multiple exceptions;
} catch (Exception1 | Exception2 | Exception3 exception){
// handle exception.
}
Run Code Online (Sandbox Code Playgroud)
捕获异常是不好的做法- 它太宽泛了,你可能会在自己的代码中错过像NullPointerException这样的东西.
对于大多数文件操作,IOException是根异常.相反,更好地抓住它.
| 归档时间: |
|
| 查看次数: |
187157 次 |
| 最近记录: |