Try/Catch Versus Throws Exception

What is the difference between try-catch and throws Exception in terms of performance?

From the paper, Optimizing Java Programs in the Presence of Exceptions:

The Java language specification requires that exceptions be precise,
which implies that:

  1. when an exception is thrown, the program state observable at the entry of the corresponding exception handler must be the same as in
    the original program; and
  2. exception(s) must be thrown in the same order as specified by the original (unoptimized) program.

To satisfy the precise exception requirement, Java compilers disable
many important optimizations across instructions that may throw an
exception...This hampers a wide range of program optimizations such as
instruction scheduling, instruction selection, loop transformations,
and parallelization.

In presence of a try-catch block, JVM maintains an exception table. For each new catch block, the compiler will add an entry to the exception table. If an exception occurs, JVM needs to go through each entry in the table and check if the exception is defined in the exception table (this requires type analysis too). The result is a much more complex control structure which in turn will greatly hamper compiler optimization.

throws on the other hand, allows the exception to propagate. Although this might be better for performance, an uncaught exception can potentially crash the thread, the whole application, or even kill the JVM itself!

How to decide when to use try-catch?

I think correctness and reliability concerns play a more important role than performance here. But if you have only performance in mind, the authors in this link have done extensive bench-marking for java code in presence of exceptions. Their most basic conclusion is that if you use exceptions for truly exceptional cases (not as a means for program flow control) there will not be much of a performance hit.

Catching versus Throwing Exceptions in Java

Throwing Exceptions

In your first example,

public void whileChatting() throws IOException{}

means that it will just throw the exception to whatever is calling the function. It can then be caught while calling that method with a try-catch block. such as

try{
whileChatting();
}
catch(IOException e){
e.printStackTrace();
}

Throwing a method basically propagates it up the chain, and so any method that calls this method will need to also include throws IOException, or the exception will need to be dealt with in the higher level method (by means of a try-catch block usually).

Catching Exceptions

Catching an exception is a way to gracefully deal with exceptions. The common thing to do is e.printStackTrace(); which prints details of the error to the console, however it's not always necessary. Sometimes you may want to do a System.exit(0) or even a System.out.println("Error in method whileCalling()")

With a catch block you can catch any type of exception! you can also do a try-catch-finally block which will run the code in the try block, catch any exceptions, and whether or not any exceptions are caught it will enter the finally block and run that code.

To know what Exception you might need to catch, you can look at the Javadocs for the class that may throw the exception. There you will find a list of every possible thing that the class can throw. You can also just catch Exception which will catch any Exception imaginable! (Well, granted it extends Exception)

And finally you can link catch blocks together like so.

try{
whileCalling();
}
catch(IOException e){
//handle this situation
}
catch(FileNotFoundException e){
//handle this situation
}
catch(Exception e){
//handle this situation
}

This will work like and else-if block and not catch duplicates.

So to answer your questions basically:

1: To throw an Exception means to have somebody else deal with it, whether this be another class, another method, or just to hoping it doesn't happen or else your program will crash(pretty bad practice).

2: To use a try catch block is to actually deal with the Exception however you see fit! printing out the stacktrace for debugging or giving the user a new prompt to re-input something maybe. (For instance a prompt that the user needs to enter a file location and then it throws a FileNotFoundException)

Hope that helps!

Why cant I use a method that throws in a catch block? Why use try/catch throw/throws in general?

First of all, it's important to understand that there are 2 types of exceptions:

  • Checked exceptions
  • Unchecked exceptions

Where the later one is all exceptions in which are inherit from RuntimeException and you shouldn't declare the throws for them in your method signature.

According to the book Hardcore Java, RuntimeException should be thrown only when the error is a programmatic error (meaning the programmer made a mistake while writing the code, and passed some invalid input for example).

In general, RuntimeException should be thrown only when the program cannot recover from the error that happened. If we can actually solve this error, we will wrap it with a try-catch block and recover from it.

As for your question specifically, the first call to Taschenrechner.divide(num1,num2); might throw checked exception (from type Exception) and therefore whoever is calling this function must do one of the following when calling divide()

  • wrap the call with try-catch block
  • declare throws on your method signature and let whoever is calling
    this method handles the exception

As for the question about efficiency - remember that sometimes you write code for someone else to use. let's say that this person passing wrong input into your code - how can you communicate to this person that something bad happened without exceptions? (or in old languages error code...)

You can learn checked/unchecked exceptions here for an example: https://howtodoinjava.com/java/exception-handling/checked-vs-unchecked-exceptions-in-java/

Usage of throws and try-catch in the same method

In your code

 void t() throws IllegalAccessException

you are telling the compiler that this code throws an exception (whether it does or not is another matter), and so any method calling this method either has to catch it or declare that it also throws it etc. etc.

As you are not actually throwing an exception from t you can remove the declaration.

void t()

Throws or try-catch

  • catch an exception only if you can handle it in a meaningful way
  • declare throwing the exception upward if it is to be handled by the consumer of the current method
  • throw exceptions if they are caused by the input parameters (but these are more often unchecked)


Related Topics



Leave a reply



Submit