When to Use Try/Catch Blocks

When to use try/catch blocks?

The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.

Don't catch an exception if you're only going to log the exception and throw it up the stack. It serves no meaning and clutters code.

Do catch an exception when you are expecting a failure in a specific part of your code, and if you have a fallback for it.

Of course you always have the case of checked exceptions which require you to use try/catch blocks, in which case you have no other choice. Even with a checked exception, make sure you log properly and handle as cleanly as possible.

Why should I not wrap every block in try-catch?

A method should only catch an exception when it can handle it in some sensible way.

Otherwise, pass it on up, in the hope that a method higher up the call stack can make sense of it.

As others have noted, it is good practice to have an unhandled exception handler (with logging) at the highest level of the call stack to ensure that any fatal errors are logged.

What's the point of try/catch blocks to catch Exceptions?

Think about the scenarios when working with a live website or application. You wouldn't want the user to see a blank screen or a screen full of error trace code. In such scenarios, potential areas of exception can be handled to show a message to the user that makes sense "sorry, you are exceeding more than 10 items in your cart etc ", "you do not have sufficient amount in your account", "username cannot have symbols ", "out service us un-operational right now please come back later".

Try catch is used to handle the such error conditions gracefully. You can enclose a code set into try and its catch would be responsible to handle it. Handling may depend on your use case but your java program wont terminate.

Abrupt termination of program doesn't let you know the actual reason of failure.

Effective use of try-catch blocks & Where should we locate them?

The code is somewhat broken.... Unless you have very specific reasons, you should never directly extend the Throwable class but should extend Exception instead (or a descendant of Exception like RuntimeException).

With the code like it is you are not likely going ot be able to catch the exception unless you catch it explicitly with catch (DatabaseAlreadyExistsException e)

Apart from that, you have a number of issues with error handling that are not recommended... doing a 'printStackTrace' is not an effective way to handle a problem, but I am not sure whether you are doing this just to show that you have handling for it, or not (i.e. does your real code just do a printStackTrace?).....


EDIT: Updated after comment...

OK, I understand what you are asking now more than I did before. Using mechanisms described in other answers and comments, I would recommend doing something like:

public boolean checkDatabaseExists(...) {
try {
... do the things you need to check the database exists.
return true;
} catch (Exception e) {
return false;
}
}

Then, in your main method, you can:

if (!checkDatabaseExists(...)) {
createDatabase(...);
}

When to use and when not to use Try Catch Finally

The answer is "it depends".

You might want to use a try{...} catch {...} around every atomic operation so that if there is a problem you can roll back to the last good state (using transactions). This may be one or several stored procedures - it depends on your application.

If you are trapping the exception, make sure you are explicit in which exceptions you catch. You shouldn't have catch (Exception ex) or catch() - known as "catch all" exception handling - but have specific catch statements like catch (IndexOutOfRangeException ex) (for example) instead.

However, if you can't handle the exception or there's nothing you can do to clean up, then you shouldn't trap it.

When to use Try Catch blocks

It seems to me that this topic is very strange and confused. Could someone lights me up?

Definitely. I'm not a PHP user, but I might have a little insight after having worked with try/catch in ActionScript, Java, and JavaScript. Bear in mind though, that different languages and platforms encourage different uses for try/catch. That said...

The only times I'd recommend using try/catch is if you're using a native language function that

  1. Can throw an error/exception
  2. Does not give you any tools to detect whether you're about to do something stupid that would cause that error/exception. eg: In ActionScript, closing a loader that is not open will result in an error but the loader doesn't have an isOpen property to check so you're forced to wrap it in try/catch to silence an otherwise totally meaningless error.
  3. The error/exception really is meaningless.

Let's take the examples you list and see how they square with that list.

I read someone saying that we should use try-catch blocks only to prevent fatal errors.

In the case of AS's loader.close() function, this is good advice. That's a fatal error, and all from an otherwise trivial misstep. On the other hand, virtually ALL errors in AS will bring your application to a halt. Would you then wrap them all in try/catch? Absolutely not! A "fatal error" is fatal for a reason. It means something terribly wrong has happened and for the application to continue on in a potentially "undefined" state is foolhardy. It's better to know an error happened and then fix it rather than just let it go.

I read someone else saying that we should use it only on unexpected errors

That's even worse. Those are presicely the errors you DON'T want to silence, because silencing them means that you're never going to find them. Maybe you're not swallowing them, though... maybe you're logging them. But why would you try/catch/log/continue as though nothing happened, allowing the program to run in a potentially dangerous and unexpected condition? Just let the error kick you in the teeth and then fix it. There's little more frustrating than trying to debug something that's wrong in a program that someone else wrote because they wrapped everything in a try/catch block and then neglected to log.

Others simply say that try-catch blocks should be used everywhere because they can be also extended (extending the Exception class).

There's potential merit to this if you're the one doing the throwing, and you're trying to alert yourself to an exceptional situation in your program... but why try/catch your own thrown error? Let it kick you in the teeth, then fix it so that you don't need to throw the error anymore.

Finally someone says that PHP try-catch block are totally useless because they are very bad implemented. (On this i find a nice SO question about performance).

Maybe so. I can't answer this one though.

So... this might be a bit of a religious question, and I'm certain people will disagree with me, but from my particular vantage point those are the lessons I've learned over the years about try/catch.

When should you use try/catch in JavaScript?

Use it whenever code you are running might throw an exception. Remember that you can throw your own errors — most of the try…catch stuff I use is for catching my own exceptions.

Is the try-catch block necessary?

The purpose of try-catch blocks is NOT to have a simple e.printStackTrace() on them, but to manage possible exceptions on the code within.

By requiring a try-catch block, Java is forcing you to deal with the exceptions that can happen in your code and make a decision on what to do with them, in order to allow your code to fail gracefully.

Moreover, if you capture an exception with a catch, code can continue to execute after, which does not happen if the exception is not captured.

How to correctly use try-catch statement

Generally, you should only use a try-catch if there is something that you can do in the catch. Can you retry the failed connection or otherwise help the user to continue? Do you want to log the exception?

If there's nothing you can do to recover or gracefully degrade, there is no point in catching the exception. Just let it bubble up to a catch at the top of the app (for example, in the Page_Error event in the base page of a web app) and handle the UI there.

How often should I use try and catch in C#?

The only down side is when an exception is actually thrown. There is no overhead for wrapping the code, except for when exceptions occur.

Also, you don't want to use try/catch for control flow. Consider this (bad code):

try {

FileStream fs = File.Open("somefile.txt", FileMode.Open);

} catch (Exception ex) {
MessageBox.Show("The file does not exist. Please select another file");
}

You'll get more performance from some thing like File.Exists. such as:

if(!File.Exists("somefile.txt"))
MessageBox.Show("The file does not exist.")

EDIT:
found the MSDN direct quote:

Finding and designing away
exception-heavy code can result in a
decent perf win. Bear in mind that
this has nothing to do with try/catch
blocks: you only incur the cost when
the actual exception is thrown. You
can use as many try/catch blocks as
you want. Using exceptions
gratuitously is where you lose
performance. For example, you should
stay away from things like using
exceptions for control flow.



Related Topics



Leave a reply



Submit