An exception is an event which occurs during the execution of code which disrupts the normal flow due to the event. When an error (exception) occurs within a method an exception object is createdwhich contains the details of the error. After the exception is created - the runtime tries to find something to handle it. The process of how the runtime handles the exception involves unwiding the stack, looks for a method that can handle the exception, or if it cannot then terminate the process and display the error to the user.
Handling the Exception
The exception will get handled - if you don't handle it. This means your user will see the message - generally highly undesireable. You should handle the exception by using a try, catch, finally block.
tryThe tey-catch-exception block will only handle exceptions thrown in the "try" area. This means you must be careful to not throw exceptions in the "catch" or "finally" blocks.
{
}
catch
{
}
finally
{
}
Handling Specific Exceptions
There are many occasions in which you want to handle the specific exception. Imaging having a file-based or zero-based exception. You could handle it gracefully rather than let the exception bubble up to the user. An example would be to handle some of the following mathematical exceptions:
- Divide by Zero (DivideByZeroException)
- Overflow (OverflowException)
- Arithmetic (ArithmeticException)
- (to name a few)
tryHandling More Than 1 Exception
{
}
catch(DivideByZeroException ex)
{
handle the exception here
}
finally
{
}
You can add additional catch blocks. Just be careful that the exception handling will be done with the first catch block that meets the exception type.
tryFinally
{
}
catch(DivideByZeroException ex1)
{ handle this exception
}
catch(Exception ex2)
{
handle all other exceptions
}
finally
{
}
The finally block is always executed, even if an exception is thrown. Use this to close any open files, close streams, or release resources. The finally block is optional.
0 comments:
Post a Comment