Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between re-throwing parameter-less catch and not doing anything?

Suppose I have the following two classes in two different assemblies:

//in assembly A
public class TypeA {
   // Constructor omitted
   public void MethodA
   {
     try {
       //do something
     }
     catch {
        throw;
     }
   }
}
//in assembly B
public class TypeB {
   public void MethodB
   {
     try {
       TypeA a = new TypeA();
       a.MethodA();
     }
     catch (Exception e)
       //Handle exception
     }
   }
}

In this case, the try-catch in MethodA just elevates the exception but doesn't really handle it. Is there any advantage in using try-catch at all in MethodA? In other words, is there a difference between this kind of try-catch block and not using one at all?

like image 316
Leo Nix Avatar asked Apr 04 '09 17:04

Leo Nix


People also ask

When should you Rethrow an exception?

If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression ( throw without assignment_expression) causes the originally thrown object to be rethrown.

What is the difference between throw and throw new exception?

throw rethrows the caught exception, retaining the stack trace, while throw new Exception loses some of the details of the caught exception. You would normally use throw by itself to log an exception without fully handling it at that point.

Is it good practice to throw exception in catch block?

It's fine practice to throw in the catch block. It's questionable practice to do so ignoring the original exception.

Why do we need Rethrowing exceptions?

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.


1 Answers

In your example, there is no advantage to this. But there are cases where it is desirable to just bubble up a specific exception.

    public void Foo()
    {
        try
        {
            // Some service adapter code

            // A call to the service
        }
        catch (ServiceBoundaryException)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw new AdapterBoundaryException("some message", ex);
        }
    }

This allows you to easily identify which boundary an exception occurred in. In this case, you would need to ensure your boundary exceptions are only thrown for code specific to the boundary.

like image 97
Mufaka Avatar answered Sep 19 '22 18:09

Mufaka