I need to work on error handling and recovery for the World of Zuul. I was wondering where usually try catch exception should be used, which processes that need them? I know that I have to use them for opening and writing to a file,,,

4 Years
Discussion Span
Last Post by mumaga

Exceptions are best used when something happens outside of the normal flow of your program. Without exceptions you would need to handle every possible situation that might occur when you write an algorithm, and then 90% of your algorithm would be devoted to handling events that happen 1% of the time, like not being able to open a file or finding a syntax error in a string that you are parsing.

By using exceptions you can clarify your algorithms by keeping them focused on the way things will happen 99% of the time, when everything is as expected. This makes it easier to write and easier to read. You can just assume that the file you need will open when you ask for it; you'd have to abort whatever you are trying to do if it didn't. You wrap things in a try { ... } when you want to pretend that something which might fail never will, then you use catch to decide what happens if something actually does fail, but catch is nicely out-of-the-way where it doesn't clutter up the code with things that almost never happen.

The important thing is not to throw an exception for something that you expect to happen often. When you throw an exception for something rare someone reading your code will probably prefer to ignore the exception; you trust that they won't feel the need to follow it and figure out how it is handled exactly. If they were to do that they would have a difficult job and you would be responsible for making it harder for them to read your code, and the more important the thing that causes the exception is, the more likely that people will want to find out where it is handled.

Sometimes you might want to throw an exception because your method is faced with a situation that it doesn't know how to handle but its caller probably does know how to handle. If this will happen frequently, then don't throw an exception. Instead, you can have the caller pass in an object and then you can call a method of that object when the situation comes up. Exceptions are only for use when someting abnormal happens.

Edited by bguild

Votes + Comments
Great post :)
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.