Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rethrow Exception Real Application

In Java 7 Rethrow Exception feature added.I know it's concept but I want to see the real application of it and why this feature needed?

like image 978
Rahim Dastar Avatar asked Oct 10 '18 08:10

Rahim Dastar


People also ask

How to rethrow an exception in Java?

How to rethrow an exception in Java? Sometimes we may need to rethrow an exception in Java. If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.

What is the purpose of re-throw an exception we caught?

Re-throw an exception we caught Re-throw wrapped exception The purpose of the rethrow operation is to propagate the exception to the higher level, But before propagation we would perform some activities like logging, send an email, audit error, rollback transaction … etc.

What is a rethrow exception in MATLAB?

rethrow (exception) rethrows a previously caught exception, exception. MATLAB ® typically responds to errors by terminating the currently running program. However, you can use a try/catch block to catch the exception. This interrupts the program termination so you can execute your own error handling procedures.

Is it safe to call rethrow_exception on multiple objects at once?

Concurrently calling rethrow_exception on exception_ptr objects that refer to the same exception is safe. Note though that some implementations may not perform a copy of the pointed object on entering the catch exception handling block, and concurrently accessing the rethrown exception object in this case may introduce a data race.


3 Answers

I will take examples from here This is the example:

  static class FirstException extends Exception { }
  static class SecondException extends Exception { }

  public void rethrowException(String exceptionName) throws FirstException, SecondException {
    try {
      if (exceptionName.equals("First")) {
        throw new FirstException();
      } else {
        throw new SecondException();
      }
    } catch (FirstException e) {
      throw e;
    }catch (SecondException e) {
      throw e;
    }
  }

This compiles with both java 6 an 7.

If you want to keep checked exceptions from method signature, you have to keep cumbersome catch clauses in java 6.

In Java 7 you can do it in following way:

public void rethrowException(String exceptionName) throws FirstException, SecondException {
  try {
    if (exceptionName.equals("First")) {
      throw new FirstException();
    } else {
      throw new SecondException();
    }
  } catch (Exception e) {
    throw e;
}

So your benefit is that you have less cumbersome catch clause.

like image 137
user987339 Avatar answered Oct 21 '22 20:10

user987339


Use Rethrowing Exceptions with More Inclusive Type Checking feature

in Java SE 7, you can specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration

When you want to declare specific exceptions that can be thrown (mainly when you are catching a generic error)

For example see Precise Rethrow example:

public static void precise() throws ParseException, IOException{
    try {
        new SimpleDateFormat("yyyyMMdd").parse("foo");
        new FileReader("file.txt").read();
    } catch (Exception e) {
        System.out.println("Caught exception: " + e.getMessage());
        throw e;
    }
}

This also make your code compliant to Sonar's Raw Exception rule.

Note you can similarly catch Throwable

like image 2
user7294900 Avatar answered Oct 21 '22 19:10

user7294900


Couple of use-cases:

  1. Using rethrow, you can edit the stacktrace information to make it more accurate. Also when needed you can hide or rid off the unnecessary internal details in stack trace.

    try     { //... }
    catch (Exception e) { throw (Exception) e.fillInStackTrace(); }
    

    Real application of fillInStackTrace is very well explained here: Why is Throwable.fillInStackTrace() method public? Why would someone use it?

    Quote from the book "Thinking in Java" written by Bruce Eckel:

    If you want to install new stack trace information, you can do so by calling fillInStackTrace( ), which returns a Throwable object that it creates by stuffing the current stack information into the old exception object

  2. Add custom message to the thrown exception. Add custom message to thrown exception while maintaining stack trace in Java

A simple example I can think of:

void fileOperator(String operationType) throws Exception(){ ... }

void fileReader() throws Exception {
    try{
        fileOperator('r');
    }
    catch(Exception e){
        throw Exception("Failed to read the file", e);
    }
}

void fileWriter() throws Exception{
    try{
        fileOperator('w');
    }
    catch(Exception e){
        throw Exception("Failed to write the file", e);
    }
}

Also, we can throw a more specific exception type (say FileReadException, FileWriteException) from the catch block.

like image 1
Saurav Sahu Avatar answered Oct 21 '22 21:10

Saurav Sahu