views:

42

answers:

2

Imagine you have some code that could potentially throw an exception. For example, you try to send an e-mail message to a mail server, or write a file to disk while you’re not sure if you have the right permissions to do so. What kind of exception handling strategy would you use to avoid the exception from being displayed in the browser? What code would you need?

A: 

All languages that can throw exceptions have some manner by which to catch them.

They often look something like this:

try
{
   some_risky_thing();
}
catch(Exception e)
{
   handle_the_exception();
}

By catching the exception you stop it's propagation up the call stack (where it will eventually find the user).

In order to stop all exceptions getting to the user put one of these at the very top level you have available. Then you can catch any stray exceptions you've missed and do something more appropriate than throw them at the user (like log them somewhere discretely).

Daniel
A: 

It depends.

For those cases, I would probably wrap the code that can throw the exception in a try/catch block. Different languages call this construct something different - sometimes it's try/catch/finally, others it's try/except.

However, it's easy to abuse exceptions and exception handling. A few things that you need to avoid are using exception handling for flow control, handling exceptions too soon (keep passing them up the call stack until they can be appropriately handled), and treating non-exceptional conditions as exceptional.

Thomas Owens