I was trying to understand why to use exceptions.
Suppose if I have an program,
(without using try/catch)
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
System.out.println(str.length());
}
I got exception
Exception in thread "main" java.lang.NullPointerException
at com.Hello.ExceptionExample.ExceptionExample.main(ExceptionExample.java:22)
Now using try/catch,
public class ExceptionExample {
private static String str;
public static void main(String[] args) {
try {
System.out.println(str.length());
} catch(NullPointerException npe) {
npe.printStackTrace();
}
}
}
I got Exception,
java.lang.NullPointerException
at com.Hello.ExceptionExample.ExceptionExample.main(ExceptionExample.java:9)
Now my question is,
In both the cases I have got the same message printed. So what is the use of using try/catch? and
What can we do after catching exception, in this case I have printed the stack trace. Is catch used only for printing the trace or for finding exception details using getMessage() or getClass()?
The difference is pretty big, actually.
Take the first one and add a line after the print:
You’ll see that
Does this execute?isn’t printed because the exception interrupts the flow of the code and stops it when it isn’t caught.On the other hand:
Will print both the stack trace and
Does this execute?. That’s because catching the exception is like saying, “We’ll handle this here and continue executing.”One other remark, the
catchblock is where error recovery should happen, so if an error occurs but we can recover from it, we put the recovery code there.Edit:
Here’s an example of some error recovery. Let’s say we have a non-existent file at
C:\nonexistentfile.txt. We want to try and open it, and if we can’t find it, show the user a message saying it’s missing. This could be done by catching theFileNotFoundExceptionproduced here:So there’s a few things to note here:
FileNotFoundExceptionand use a custom error message instead of printing the stack trace. Our error message is cleaner and more user-friendly than printing a stack trace. In GUI applications, the console may not even be visible to the user, so this may be code to show an error dialog to the user instead. Just because the file didn’t exist doesn’t mean we have to stop executing our code.throws IOExceptionin the method signature instead of catching it alongside theFileNotFoundException. In this particular case, theIOExceptionwill be thrown here if we fail to read the file even though it exists. For this method, we’re saying that handling errors we encounter while reading the file isn’t our responsibility. This is an example of how you can declare an irrecoverable error (by irrecoverable, I mean irrecoverable here, it may be recoverable somewhere further up, such as in the method that calledprintFileToConsole).finallyblock here, so I’ll explain what it does. It guarantees that if theScannerwas opened and an error occurs while we’re reading the file, theScannerwill be closed. This is important for many reasons, most notably that if you don’t close it, Java will still have the lock on the file, and so you can’t open the file again without exiting the application.