Java中if语句中的异常处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20858992/
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
Exception handling within if statements in Java
提问by dwwilson66
I'm a relative newbie to custom error handling in Java, and I'm trying to figure out how to use catch
statements to deliver specific messages inside of an if statement. I wanted to get some extra sets of eyes to look at what I'm trying to do and offer feedback before I completely overthink this and overdo it too badly.
我是 Java 中自定义错误处理的相对新手,我正在尝试弄清楚如何使用catch
语句在 if 语句中传递特定消息。我想在我完全过度考虑这件事并且做得太过分之前,让一些额外的眼睛来看看我正在尝试做什么并提供反馈。
Consider: We have a directory of hourly log files and I have an on-demand reporting job creates a concatenation of all today's log files created so far. I want to add a step that checks for the existence of a concatenated log file, deletes it then creates it if present, or just creates it if it's not present. With the code below, I'm returning an exception if, for some reason, the new file cannot be created.
考虑一下:我们有一个每小时日志文件的目录,我有一个按需报告作业创建迄今为止创建的所有今天的日志文件的串联。我想添加一个步骤来检查连接的日志文件是否存在,删除它然后创建它(如果存在),或者如果它不存在就创建它。使用下面的代码,如果由于某种原因无法创建新文件,我将返回异常。
try {
File file = new File (destinationPath + "todayToNowLogFile.csv");
if(file.exists())
{
if(file.delete())
{
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Existing file cannot be deleted.")
}
} else {
System.out.println("File will be created.");
}
}
//
catch(Exception e) {
System.err.println("Exception: ");
System.out.println("Exception: "+ e.getMessage().getClass().getName());
e.printStackTrace();
}
Now, in the case where the file cannot be deleted, I would like to display the exception preventing file deletion. First, I would need to catch
that error, but then where do I put the try
?
现在,在无法删除文件的情况下,我想显示阻止文件删除的异常。首先,我需要catch
那个错误,然后我把try
?
Doing something like this...
做这样的事情...
try
{
if(file.delete())
{
System.out.println(file.getName() + " is deleted!");
}
}
else {
catch(Exception eDel) {
System.err.println("Exception: ");
System.out.println("Exception: "+ eDel.getMessage().getClass().getName());
eDel.printStackTrace();
}
}
....interrupts the if...then
block. I'm not sure how to insert a try...catch
within an if...then
. Is there a way to do this? Or does my original code catch EVERY error associated with ANY operation on the file
defined in the try
block, and I would need to put if...then
logic in the catch
block, something along the lines of this pseudocode....
....中断if...then
块。我不确定如何try...catch
在if...then
. 有没有办法做到这一点?或者我的原始代码是否捕获与块中file
定义的任何操作相关的每个错误try
,我需要将if...then
逻辑放入catch
块中,类似于此伪代码的行...
catch(Exception e) {
if(exception relates to file deletion) {
"File delete exception " + exceptionMessages;
} else if(exception relates to file creation) {
"File create exception " + exceptionMessages;
} else if(other exception) {
"other exception " + exceptionMessage;
} else {
"no exceptions encountered"
}
}
What's the most appropriate way to handle this type of situation?
处理这种情况的最合适的方法是什么?
回答by user987339
You should think of try/catch
as any other statement. So you can put it inside any of two branches of if/then/else
statement, but it have to be whole inside:
您应该将其try/catch
视为任何其他陈述。所以你可以把它放在if/then/else
语句的两个分支中的任何一个中,但它必须是完整的:
if(statement){
...
try{
...
}catch(...){
...
}
...
}else{
...
try{
...
}catch(...){
...
}
...
}
If you have to catch multiple exceptions you can achieve this by multiple catch parts:
如果您必须捕获多个异常,您可以通过多个捕获部分来实现:
try{
...
}catch(Exception1 e1){
...
}catch(Exception2 e2){
...
}catch(Exception3 e3){
...
}
回答by DmiN
At first you should check if any method could throw any specific Exceptions. You could do this by looking into the Javadoc or use your favorite IDE.
首先你应该检查是否有任何方法可以抛出任何特定的异常。您可以通过查看 Javadoc 或使用您喜欢的 IDE 来完成此操作。
If you catch Exception as the Exception class, it catches every Exception that is subclass of it.
如果您将 Exception 作为 Exception 类捕获,它会捕获作为它的子类的每个 Exception。
If you want to have specific Exception handling, e.g. for an IOException like in the delete() method, you can catch every specific Exceptionclass or use multi-catch in Java 7
如果您想要特定的异常处理,例如像 delete() 方法中的 IOException,您可以捕获每个特定的 Exceptionclass 或在 Java 7 中使用 multi-catch
try {
do regular code that can throw exceptions
} catch(Exception e) {
it catches every Exception that is a subclass of Exception.
You handle every exception raised in the try block above by the same way
}
If you want to handle exceptions in different ways, e.g. print different messages, just do this like the following example:
如果您想以不同的方式处理异常,例如打印不同的消息,只需像以下示例一样执行此操作:
try {
do sth
} catch (SpecificExceptionclass sec) {
do sth specific for this exception
} catch (AnotherExceptionClass aec) {
do sth else
}
Or just use Multicatch in Java 7, if you want to have same exception handling for some specific exception classes:
或者只是在 Java 7 中使用 Multicatch,如果您想对某些特定的异常类进行相同的异常处理:
try {
do sth
} catch (SpecificExceptionclass | AnotherExceptionClass e) {
do sth specific for this exception
}
To achieve different Exceptions thrown in your code the methods should at least throw different exceptions. In your example with file.exists() and file.delete() there's only an IOException thrown by your code, so there is no use of specific exception handling.
为了实现代码中抛出的不同异常,这些方法至少应该抛出不同的异常。在您使用 file.exists() 和 file.delete() 的示例中,您的代码只抛出了一个 IOException ,因此没有使用特定的异常处理。
回答by user2810910
I think it would be a good idea to put your code in a function that returns true or false.
1: True means the file does not exist and was created
2: False means the file exists and was deleted.
3: An exception if the file exists but cant be deleted.
Also provide a separate function to determine if the file exists or not.
Your javadoc at the top of your functions should explain the above so the caller of your functions don't have to look at their content to determine how to use them.
Note an exception is an unusual event and shouldn't be thrown to indicate the state of inserting/deleting. It should be reserved for unusual conditions which the caller normally wouldn't encounter.
A note on exceptions: If you have a large project with 1000 classes each of which has on average 20 functions, that's 20000 functions. Its not practical to pepper each function with excessive exception handling (such as checking for nulls passed in as arguments). A solution to this is to handle checked exceptions in the java language (FileIO) and let (the bulk) of unchecked exceptions ripple up the function call chain until you leave all your business logic and are about to display the results. You only catch them if you want to add additional information to the exception before rethrowing it. Example: adding the primary key value of the record of an SQLExeption being thrown so you know what record is causing problems. Just before you return to the user, log the stack trace and display a simplified message to the user (not the stack trace). The caller of your function should read its javadoc to see how to use it. If he violates your javadoc, the function may or may not throw an exception. Its his reponsibility to follow the javadoc. Last point: your project should have general coding policies for the entire project to prevent some types of exceptions from accidently being introduced by the caller such as: all functions are not epected to recieve nulls as arguments or will return a null unless specified in its javadoc. All functions will accept as arguments (or return) empty lists or empty strings correctly unless specified in their javadoc.
我认为将代码放在返回 true 或 false 的函数中是个好主意。
1:真表示文件不存在,已创建
2:假表示文件存在,已删除。
3:文件存在但无法删除的异常。
还提供了一个单独的函数来确定文件是否存在。
函数顶部的 javadoc 应该解释上述内容,这样函数的调用者就不必查看它们的内容来确定如何使用它们。
请注意,异常是一个不寻常的事件,不应抛出以指示插入/删除的状态。它应该保留用于调用者通常不会遇到的异常情况。
关于异常的说明:如果您有一个包含 1000 个类的大型项目,每个类平均有 20 个函数,那就是 20000 个函数。对每个函数进行过多的异常处理(例如检查作为参数传入的空值)是不切实际的。对此的解决方案是在 Java 语言 (FileIO) 中处理已检查的异常,并让(大部分)未检查的异常在函数调用链中波动,直到您离开所有业务逻辑并即将显示结果。如果您想在重新抛出异常之前向异常添加其他信息,则只能捕获它们。示例:添加被抛出的 SQLExeption 记录的主键值,以便您知道是什么记录导致了问题。就在返回给用户之前,记录堆栈跟踪并向用户显示一条简化消息(不是堆栈跟踪)。函数的调用者应该阅读它的 javadoc 以了解如何使用它。如果他违反了您的 javadoc,该函数可能会也可能不会抛出异常。遵循 javadoc 是他的责任。最后一点:您的项目应该为整个项目制定通用的编码策略,以防止调用者意外引入某些类型的异常,例如:除非在其 javadoc 中指定,否则所有函数都不应接收空值作为参数或将返回空值. 除非在它们的 javadoc 中指定,否则所有函数都将正确接受作为参数(或返回)空列表或空字符串。您的项目应该有整个项目的通用编码策略,以防止调用者意外引入某些类型的异常,例如:除非在其 javadoc 中指定,否则所有函数都不会接收空值作为参数或将返回空值。除非在它们的 javadoc 中指定,否则所有函数都将正确接受作为参数(或返回)空列表或空字符串。您的项目应该有整个项目的通用编码策略,以防止调用者意外引入某些类型的异常,例如:除非在其 javadoc 中指定,否则所有函数都不会接收空值作为参数或将返回空值。除非在它们的 javadoc 中指定,否则所有函数都将正确接受作为参数(或返回)空列表或空字符串。
回答by Dinesh Arora
What you want here is to create your own Exception class.
您在这里想要的是创建您自己的 Exception 类。
To create an exception class say you need to extend Exception class. Here's an example.
Lets say my custom exception class should be named as MyFileErrorException
要创建异常类,请说您需要扩展 Exception 类。这是一个例子。假设我的自定义异常类应该命名为MyFileErrorException
So I create a new class like this -
所以我创建了一个这样的新类 -
class MyFileErrorException extends Exception {
private String message = null;
public MyFileErrorException() {
super();
}
public MyFileErrorException(String message) {
super(message);
this.message = message;
}
public MyFileErrorException(Throwable cause) {
super(cause);
}
@Override
public String toString() {
return message;
}
@Override
public String getMessage() {
return message;
}
}
Now I need to throw this exception at will. So in Your case you wantto catch File delete exception so the code will like this -
现在我需要随意抛出这个异常。因此,在您的情况下,您想要捕获文件删除异常,因此代码会像这样 -
if(file.delete())
{
System.out.println(file.getName() + " is deleted!");
} else {
try{
System.out.println("Existing file cannot be deleted.")
throw new MyFileErrorException("File Could not be deleted val is null");
}catch(MyFileErrorException ex){
//Do wahtever you want to do
}
}