-1

I don't want to throw Runtime Exceptions. I always enclose my code with try-catch block. So if there is any exception, it will be immediately be caught.

I know this is not a good programming practice, but I am quite keen to know whether there will be any performance issue for taking this approach?

blackpanther
  • 10,998
  • 11
  • 48
  • 78
Skabdus
  • 220
  • 3
  • 13
  • How Slow are java exceptions? http://stackoverflow.com/questions/299068/how-slow-are-java-exceptions – Eric Leschinski Feb 19 '14 at 06:38
  • http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html – Brian Roach Feb 19 '14 at 06:49
  • I wouldn't call *always* doing it "not a good practice", I'd call it terrible at best. There's no worse idea than swallowing exceptions and there aren't many methods which can meaningfully handle them. – maaartinus Feb 19 '14 at 06:51

2 Answers2

1

Well, it depends - mostly on what your application is doing, and what possible runtime failures can come up.

Let's categorize runtime exceptions into two buckets: those that we can recover from, and those that we shouldn't recover from.

First, if you have a method that looks like this:

public boolean validateInteger(Integer value) {
    return value > 0;
}

...then you'll notice that there's a possible NullPointerException that could come up as a result of value being null. That means that you had bad data coming in and you dealt with it in an inappropriate manner.

Heaven help you if you do this:

Integer value = null;
try {
    boolean result = validateInteger(value);
} catch (RuntimeException e) {
    e.printStackTrace();
}

What you're doing is ignoring the bad input instead of checking the boundaries. This can lead to a multitude of bugs and logic errors. We shouldn't be continuing on this error.

If, on the other hand, you can recover from some catastrophic "Java can't continue" error, then it'd be safe to do so.

Take a standard formatter used to parse a date, allowing the user to specify their own format.

Formatter formatter = new Formatter();
Date date = new Date();
System.out.println(formatter.format(userProvidedFormat, date);

That could realistically blow up if they mess up the format. Why do we want to stop everything instead of asking the user to provide another format? This is the kind of error we can recover from.

This also adds a bit to the notion of checked exceptions - the API truly believes that the exceptional state you get back is recoverable, so you should be recovering from it.

Makoto
  • 104,088
  • 27
  • 192
  • 230
-1

Sometimes you will get exceptions which are not because of your code/method... Assume if a parent method (caller) passes an invalid argument and you try to use it, you will get an exception... Now, since its the parent who is responsible for the error, only it should handle it.. Not your method... If the exception is due to your code only, then you can have a try-catch block...

TheLostMind
  • 35,966
  • 12
  • 68
  • 104