在Java中,捕获泛型异常和特定异常(例如IOException?)之间有什么区别? [英] In Java, what is the difference between catch a generic exception and a specific exception (eg. IOException?)

查看:166
本文介绍了在Java中,捕获泛型异常和特定异常(例如IOException?)之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我只捕捉到通用异常,但是我想改变这个来捕捉特定的异常,但是这有什么优势?

Currently I'm catching only generic exceptions, but i want change this to catch the specific exceptions, but what is the advantage of this?

推荐答案

执行一般的try / catch语句和捕获特定异常(例如FileNotFoundException)之间的区别通常取决于需要处理哪些错误以及您不需要担心的错误。例如:

The difference between performing a general try/catch statement and catching a specific exception (e.g. a FileNotFoundException) typically depend on what errors you need to handle and what errors you don't need to worry about. For instance:

catch (Exception e) {    //A (too) general exception handler
...
}

上面的代码将捕获抛出在try语句内的每个异常。但也许你不想处理每个错误。你可以用OutOfMemory异常做什么?

The code above will catch EVERY exception that is thrown inside of the try statement. But maybe you don't want to handle every error. What can you do with an "OutOfMemory" exception?

一个更好的错误处理方法是执行一些默认动作,如果错误是未知的或者你不能做任何事情,并执行另一个动作,如果你发现如果你抓到,你可以做计划B。

A better method of error handling would be to perform some default action if the error is unknown or something you can't do anything about, and perform another action if you discover that you can do "Plan B" if you catch.

例如,假设你试图打开一个文件,但该文件不存在。您可以捕获FileNotFoundException并创建一个新的空白文件,如下所示:

For example, assume you are trying to open a file, but the file doesn't exist. You can catch the FileNotFoundException and create a new blank file as below:

catch (FileNotFoundException e) {    //A specific exception handler
    //create a new file and proceed, instead of throwing the error to the user
}catch (Exception e) {    //For all other errors, alert the user
    ...
}

这是一个最有效和用户友好的错误检查方法,过去曾经使用过。

This has been the most effective and user-friendly method of error checking that I've used in the past.

这篇关于在Java中,捕获泛型异常和特定异常(例如IOException?)之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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