如何捕获通过阅读和写入文件将抛出的所有异常? [英] How can I catch all the exceptions that will be thrown through reading and writing a file?

查看:116
本文介绍了如何捕获通过阅读和写入文件将抛出的所有异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

h2_lin>解决方案

如果需要,可以在方法中添加throws子句。那么你不必马上赶上检查方法。这样,您可以稍后(或许与其他异常同时)捕获异常



代码看起来像:

  public void someMethode()throws SomeCheckedException {

//代码

}

可以处理异常,如果你不想以这种方法处理它们。



捕获所有异常一些代码块可能会抛出你可以做的:(这也将捕获异常你自己写的)

  try {

//特殊的代码块...

// ...

} catch例外e){

//按照你的要求处理e。
// e可能是任何类型的异常。

}

原因是因为异常是所有异常的基类。因此,任何可能抛出的异常都是一个异常(大写'E')。



如果要处理自己的异常,首先只需在通用异常之前添加一个 catch 块。 p>

  try {
} catch(MyOwnException me){
} catch(Exception e){
}


In Java, is there any way to get(catch) all exceptions instead of catch the exception individually?

解决方案

If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions later (perhaps at the same time as other exceptions).

The code looks like:

public void someMethode() throws SomeCheckedException {

    //  code

}

Then later you can deal with the exceptions if you don't wanna deal with them in that method.

To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)

try {

    // exceptional block of code ...

    // ...

} catch (Exception e){

    // Deal with e as you please.
    //e may be any type of exception at all.

}

The reason that works is because Exception is the base class for all exceptions. Thus any exception that may get thrown is an Exception (Uppercase 'E').

If you want to handle your own exceptions first simply add a catch block before the generic Exception one.

try{    
}catch(MyOwnException me){
}catch(Exception e){
}

这篇关于如何捕获通过阅读和写入文件将抛出的所有异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆