简体   繁体   中英

Is the try-catch block necessary?

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?

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.

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. Eg: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM