41

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:

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.

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.

Nick
  • 1,743
  • 6
  • 23
  • 38
  • 11
    You should **never** ignore exceptions. You should **never** catch `Exception`. Either you plan to catch and handle a **specific** exception or you cannot handle it, and let it percolate up the stack. – Boris the Spider Feb 22 '15 at 15:18
  • 2
    remove `throws` from the method signature of `setSomething1(int a);` – Bhargav Modi Feb 22 '15 at 15:18
  • 1
    In my experience stating "probably won't" *almost certainly will*, simply by Murphy's Law. And if you've hidden the exception, you won't know when it does. – Andy Turner Feb 22 '15 at 15:18
  • @BoristheSpider - it's OK to catch it if you subsequently rethrow it. – Andy Turner Feb 22 '15 at 15:21
  • @AndyTurner that really depends. It's rarely a good idea to catch `Exception`. – Boris the Spider Feb 22 '15 at 15:22
  • @BoristheSpider OK, it *can* be OK to catch it then. I totally agree it is best avoided. – Andy Turner Feb 22 '15 at 15:23
  • 1
    @AndyTurner Catching and rethrowing is always OK with respect to the propagation of exceptions. However, the common mistake is to catch, *log*, and rethrow. Repeated on several layers on the call stack, this results in the notorious polution of the logs with repeated error messages. – Marko Topolnik Feb 22 '15 at 15:28

8 Answers8

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

Use the word ignore after the Exception keyword.

Joe Almore
  • 4,036
  • 9
  • 52
  • 77
40

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:

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));
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • Can I do something like this? >> `ignoringExc(() -> { /* code inside */ });` – Ωmega Mar 05 '18 at 12:19
  • @Ωmega Yes you can. `() -> {}` is [lambda](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) – Superior Jun 13 '20 at 13:03
  • 1
    I suggest to not use the global Exception type and instead use the exact exception that we are trying to ignore. This is because it is risky to ignore all exceptions blindly, and maybe we can add log inside the catch exception and use a lower level logging like trace or debug. – user666 Oct 14 '21 at 06:27
  • Just to simplify the above - there is no need to create a new functional interface - the built-in `java.util.concurrent.Callable` has a `call()` method that throws the generic `Exception` ([source](https://stackoverflow.com/questions/22687943/)) – ManSamVampire Apr 06 '23 at 15:15
7

IntelliJ Idea IDE suggests to rename a variable to ignored

when it isn't used.

This is my sample code.

try {
    messageText = rs.getString("msg");
    errorCode = rs.getInt("error_code");
} catch (SQLException ignored) { }
ivanoklid
  • 81
  • 1
  • 4
2

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?

Dogs
  • 2,883
  • 1
  • 19
  • 15
2

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 :

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);
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
1

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.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
1

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:

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();
}
user25839
  • 73
  • 5
1

Those who write empty catch blocks shall burn in the Hell for the eternity.

Or worse, they will be forced to debug the damn rubbish they wrote forever and ever.

That said, one thing you might want to do is writing exception handling in a less verbose way. The NoException library is very good at that.

zakmck
  • 2,715
  • 1
  • 37
  • 53