如何忽略 Java 中的异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28659462/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:35:04  来源:igfitidea点击:

How to ignore Exceptions in Java

javaexceptionexception-handling

提问by Nick

I have the following code:

我有以下代码:

TestClass test=new TestClass();
test.setSomething1(0);  //could, but probably won't throw Exception
test.setSomething2(0);  //could, but probably won't throw Exception

I would like to execute: test.setSomething2(0);even if test.setSomething(0)(the line above it) throws an exception. Is there a way to do this OTHER than:

我想执行:test.setSomething2(0);即使test.setSomething(0)(上面的行)抛出异常。除了:

try{
   test.setSomething1(0);
}catch(Exception e){
   //ignore
}
try{
   test.setSomething2(0);
}catch(Exception e){
   //ignore
}

I have a lot of test.setSomething's in a row and all of them could throw Exceptions. If they do, I just want to skip that line and move to the next one.

我连续有很多 test.setSomething,它们都可能抛出异常。如果他们这样做,我只想跳过该行并转到下一行。

For clarification, I don't care if it throws an Exception, and I can't edit the source code of the code which throws this exception.

为了澄清起见,我不在乎它是否抛出异常,并且我无法编辑抛出此异常的代码的源代码。

THIS IS A CASE WHERE I DON'T CARE ABOUT THE EXCEPTIONS (please don't use universally quantified statements like "you should never ignore Exceptions"). I am setting the values of some Object. When I present the values to a user, I do null checks anyway, so it doesn't actually matter if any of the lines of code execute.

这是一个我不关心例外的情况(请不要使用像“你永远不应该忽略例外”这样的通用量化语句)。我正在设置某个对象的值。当我向用户提供这些值时,无论如何我都会进行空值检查,因此是否执行任何代码行实际上并不重要。

采纳答案by Marko Topolnik

I would gravely doubt the sanity of any testing code which ignores exceptions thrown from tested code. That said, and assuming that you know what you are doing... there is no way to fundamentally ignore a thrown exception. The best that you can do is minimize the boilerplate you need to wrap the exception-throwing code in.

我会严重怀疑任何忽略从测试代码抛出的异常的测试代码的理智。也就是说,假设您知道自己在做什么……没有办法从根本上忽略抛出的异常。你能做的最好的事情就是最小化你需要包装异常抛出代码的样板。

If you are on Java 8, you can use this:

如果您使用的是 Java 8,则可以使用以下命令:

public static void ignoringExc(RunnableExc r) {
  try { r.run(); } catch (Exception e) { }
}

@FunctionalInterface public interface RunnableExc { void run() throws Exception; }

Then, and implying static imports, your code becomes

然后,并暗示静态导入,您的代码变为

ignoringExc(() -> test.setSomething1(0));
ignoringExc(() -> test.setSomething2(0));

回答by Dogs

Unfortunately no, there isn't, and this is by intention. When used correctly, exceptions should not be ignored as they indicate that something didn't work and that you probably shouldn't continue down your normal execution path. Completely ignoring exceptions is an example of the 'Sweep it under the rug' anti-pattern, which is why the language doesn't support doing so easily.

不幸的是,不,没有,这是故意的。如果使用得当,不应忽略异常,因为它们表明某些事情不起作用,并且您可能不应该继续沿着正常的执行路径前进。完全忽略异常是“把它扫到地毯下”反模式的一个例子,这就是为什么该语言不支持这样做的原因。

Perhaps you should look at why TestClass.setSomething is throwing exceptions. Is whatever you're trying to 'test' really going to be valid if a bunch of setter methods didn't work correctly?

也许你应该看看为什么 TestClass.setSomething 会抛出异常。如果一堆 setter 方法不能正常工作,那么你试图“测试”的东西真的有效吗?

回答by Lajos Arpad

You should not ignore Exceptions. You should handle them. If you want to make your test code simple, then add the try-catch block into your functions. The greatest way to ignore exceptions is to prevent them by proper coding.

您不应该忽略异常。你应该处理它们。如果您想让您的测试代码简单,那么将 try-catch 块添加到您的函数中。忽略异常的最好方法是通过适当的编码来防止它们。

回答by Jean-Baptiste Yunès

You can't ignore exception in Java. If a method declares being able to throw something this is because something important can't be done, and the error can't be corrected by the method designer. So if you really wan't to simplify your life encapsulate the method call in some other method like this :

您不能忽略 Java 中的异常。如果一个方法声明能够抛出一些东西,这是因为一些重要的事情无法完成,并且方法设计者无法纠正错误。因此,如果您真的不想简化您的生活,请将方法调用封装在其他一些方法中,如下所示:

class MyExceptionFreeClass {
  public static void setSomething1(TestClass t,int v) {
    try {
      t.setSomething1(v);
    } catch (Exception e) {}
  public static void setSomething2(TestClass t,int v) {
    try {
      t.setSomething2(v);
    } catch (Exception e) {}
}

and call it when you need it:

并在需要时调用它:

TestClass test=new TestClass();
MyExceptionFreeClass.setSomething1(test,0);
MyExceptionFreeClass.setSomething2(test,0);

回答by Joe Almore

try {
 // Your code...
} catch (Exception ignore) { }

Use the word ignoreafter the Exceptionkeyword.

使用关键字ignore后的单词Exception

回答by ivanoklid

IntelliJ Idea IDE suggests to rename a variable to ignored

IntelliJ Idea IDE 建议将变量重命名为 ignored

when it isn't used.

不使用的时候。

This is my sample code.

这是我的示例代码。

try {
    messageText = rs.getString("msg");
    errorCode = rs.getInt("error_code");
} catch (SQLException ignored) { }

回答by user25839

I know this is old, but I do think there are occasions when you want to ignore an exception. Consider you have a string that contains a delimited set of parts to be parsed. But, this string can sometimes contain say, 6 or 7 or 8 parts. I don't feel that checking the len each time in order to establish an element exists in the array is as straight forward as simply catching the exception and going on. For example, I have a string delimited by '/' character that I want to break apart:

我知道这很旧,但我确实认为有时您想忽略异常。假设您有一个字符串,其中包含一组要解析的分隔部分。但是,这个字符串有时可以包含 6 或 7 或 8 个部分。我认为每次检查 len 以建立数组中存在的元素并不像简单地捕获异常并继续那样直接。例如,我有一个由 '/' 字符分隔的字符串,我想将其分开:

public String processLine(String inLine) {
    partsArray = inLine.split("/");

    //For brevity, imagine lines here that initialize
    //String elems[0-7] = "";

    //Now, parts array may contains 6, 7, or 8 elements
    //But if less than 8, will throw the exception
    try {
        elem0 = partsArray[0];
        elem1 = partsArray[1];
        elem2 = partsArray[2];
        elem3 = partsArray[3];
        elem4 = partsArray[4];
        elem5 = partsArray[5];
        elem6 = partsArray[6];
        elem7 = partsArray[7];
    catch (ArrayIndexOutOfBoundsException ignored) { }

    //Just to complete the example, we'll append all the values
    //and any values that didn't have parts will still be
    //the value we initialized it to, in this case a space.
    sb.append(elem0).append(elem1).append(elem2)...append(elem7);

    //and return our string of 6, 7, or 8 parts
    //And YES, obviously, this is returning pretty much
    //the same string, minus the delimiter.
    //You would likely do things to those elem values
    //and then return the string in a more formatted way.
    //But was just to put out an example where
    //you really might want to ignore the exception
    return sb.toString();
}