Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thoughts on try-catch blocks

What are your thoughts on code that looks like this:

public void doSomething()
{
    try
    {
       // actual code goes here
    }
    catch (Exception ex)
    {
        throw;
    }
}

The problem I see is the actual error is not handled, just throwing the exception in a different place. I find it more difficult to debug because i don't get a line number where the actual problem is.

So my question is why would this be good?

---- EDIT ----

From the answers it looks like most people are saying it's pointless to do this with no custom or specific exceptions being caught. That's what i wanted comments on, when no specific exception is being caught. I can see the point of actually doing something with a caught exception, just not the way this code is.

like image 986
John Boker Avatar asked Apr 15 '09 13:04

John Boker


People also ask

Is try catch block good practice?

It is perfectly fine to use two try/catch blocks if the algorithm requires it. I have often used a new try/catch in a catch block to ensure a safe cleanup so a blanket statement is not possible. +1 Agreed.

What is the purpose of try catch blocks?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Is a catch block needed?

is it necessary to put catch after try block ? Nope, not at all. Its not mandatory to put catch after try block, unless and until the try block is followed by a finally block. Just remember one thing, after try, a catch or a finally or both can work.

Is it good to write code in catch block?

Catch blocks should not be used for writing code logic. They should be used only for handling errors.


1 Answers

Depending on what quality you are looking at it is not throwing the exception in a different place. "throw" without a target rethrows the exception which is very different from throwing an exception. Primarily a rethrow does not reset the stack trace.

In this particular sample, the catch is pointless because it doesn't do anything. The exception is happily rethrown and it's almost as if the try/catch didn't exist.

like image 99
JaredPar Avatar answered Sep 21 '22 10:09

JaredPar