2

I started learning Java and I got confused about the necessity of try-catch blocks in some cases.

Let's say I have the following in my code:

System.out.println(args[0]);

If I don't have any arguments, I get the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Main.main ...

But I wondered why do I need a try-catch block, with e.printStackTrace() in it, if the output will be the same as above and I also could identify the problem?

Fogarasi Norbert
  • 650
  • 2
  • 14
  • 34
  • 1
    you can use a try-catch block and ignore the error which is thrown. this is good if the error doesn't influence your program and if it should keep running even if you have no arguments passed – XtremeBaumer May 23 '17 at 11:39
  • 2
    @XtremeBaumer *"this is good if the error doesn't influence your program"* This is pretty unlikely, or even impossible. It wouldn't be an error if it wouldn't influence the programm. What you mean are exceptions. – Tom May 23 '17 at 11:41

2 Answers2

4

The purpose of try-catch blocks is NOT to have a simple e.printStackTrace() on them, but to manage possible exceptions on the code within.

By requiring a try-catch block, Java is forcing you to deal with the exceptions that can happen in your code and make a decision on what to do with them, in order to allow your code to fail gracefully.

Moreover, if you capture an exception with a catch, code can continue to execute after, which does not happen if the exception is not captured.

Roc Aràjol
  • 190
  • 9
  • 2
    Also, it is worth noting that Java does not always *force* you to catch an exception (https://stackoverflow.com/questions/6115896/java-checked-vs-unchecked-exception-explanation). In the provided example, it makes no sense to catch `ArrayIndexOutOfBoundsException`, because it results from a *programming error*, not an *abnormal runtime condition* – crizzis May 23 '17 at 11:50
3

It is not necessary to catch all exceptions. In Java there is two types of exceptions: checked and unchecked. The rule is simple a checked exception has to be handled by the caller while an unchecked exception can be handled either by not catching it, or by catching it.

In your case since ArrayIndexOutOfBoundsException is an unchecked exception, you don't necessarily have to catch it . However if it is not handled your application will crash. Sometimes you want to save your app in case of an error, and in this case catching the exception is the way to do it. E.g: You ask an url from the user and try to connect to it. If the URL was invalid it will throw an exception. But instead of letting your application to crash you might want to notify the user and ask a new URL. So you will catch the exception and do the error handling.

Basically, to do a simply e.printStackTrace() is a bad practice. Do real error handling on the catch block or throw it away.

prashant
  • 1,382
  • 1
  • 13
  • 19
Balázs Nemes
  • 699
  • 4
  • 9