Please enable JavaScript.
Coggle requires JavaScript to display documents.
CHAPTER 6: Managing errors and exceptions (Outline (■ Handle exceptions by…
CHAPTER 6: Managing errors and exceptions
Outline
■ Handle exceptions by using the try, catch, and finally statements.
■ Control integer overflow by using the checked and unchecked keywords.
■ Raise exceptions from your own methods by using the throw keyword.
■ Ensure that code always runs, even after an exception has occurred, by using a finally block.
try & catch
try
When the code runs, it attempts to
execute all the statements in the try block, and if none of the statements generates an exception,
they all run, one after the other, to completion.
However, if an error condition occurs,
execution jumps out of the try block and into another piece of code designed to catch and
handle the exception—a catch handler.
catch
A catch handler is intended to capture and
handle a specific type of exception, and you can have multiple catch handlers after a try
block, each one designed to trap and process a specific exception; you can provide different
handlers for the different errors that could arise in the try block.
General exception
catch (Exception ex) // this is a general catch handler
{
//...
}
HOWEVER, always put more specific exception handlers before the general ones
Unhandled exceptions
If code is written in a try block and there is an error it jumps to the catch blocks
If no catch handles this exception the computer immediately exits the method and goes to the method call
This cycle repeats until a catch block handling this exception is found
If no such catch block exists then the program terminates with an unhandled exception.
Tips
Be smart about where you put your try and catch blocks.
Placing them where they are originally called seems to be the best place as of now
#
you can turn on overflow checking
What happens if we add 1 to an int which happens to be the largest an int can be,2147483647?
It takes it to the negative largest number which would something we don't want
In order to be extra cautious you can turn on an option in visual studios to check this
check and unchecked
Used only for int type
Check
Syntax
checked
{
int willThrow = number++;
Console.WriteLine(“this won’t be reached”);
}
The statements in the checked will throw an OverflowException if an overflow occurs
Unchecked
Syntax
The statements in the checked will NOT throw an OverflowException if an overflow occurs
For both
If a method call is inside a check or unchecked does not
apply to code that runs in the method that is called.
Since we are throwing exceptions they require a catch block