Lecture #7 Error Handling, Debugging
Lecture #7 Error Handling, Debugging
• Error Handling
• Debugging
…
Error/Exception Handling
For example,
int divideByZero = 7 / 0;
int a = 5, b = 0;
Runtime Errors (Exceptions) int result = a / b; // DivideByZeroException
int a = 5, b = 6;
double avg = a + b / 2.0; // logical error, it should be
Logical Errors (a + b) / 2.0
Exception Handling
C# exception handling is built upon four keywords:
try, catch, finally, and throw.
Keyword Definition
try {
try // statements causing exception
{ } catch( ExceptionName e1 ) {
// code that may raise an exception // error handling code
} } catch( ExceptionName e2 ) {
catch (Exception e) // error handling code
{ finally {
// code that handles the exception // statements to be executed
} }
Example
try
{
int num = 0;
int divideByZero = 7 / num;
}
catch (Exception e)
{
Console.WriteLine("Exception has occurred");
}
Example
static void Main()
{
string[] colors = { "Red", "Blue", "Green" };
try
{
// code that may raise an exception
Console.WriteLine(colors[5]);
}
catch (Exception e)
{
Console.WriteLine("An exception occurred: " + e.Message);
}
}
An exception occurred: Index was outside the
bounds of the array.
Finally block
We can also use finally block with try and try
catch block. The finally block is always {
executed whether there is an exception int[] myNumbers = {1, 2, 3};
or not. Console.WriteLine(myNumbers[10]);
}
try
catch (Exception e)
{
{
// code that may raise an exception
Console.WriteLine("Something went wrong.");
}
}
catch (Exception e)
finally
{
{
// code that handles the exception
Console.WriteLine("The 'try catch' is finished.");
}
}
finally
{
// this code is always executed Something went wrong.
} The 'try catch' is finished.
Common .NET Exceptions
1. System.IndexOutOfRangeException – Occurs attempting to access an array element that does not exist
2. System.IO.IOException – Used around many file I/O type operations
3. System.Data.SqlClient.SqlException – Various types of SQL Server exceptions
4. System.OutOfMemoryException – If your app runs out of memory
5. System.InvalidCastException – When attempting to convert an object to an incompatible type
6. System.InvalidOperationException – Common generic exception in a lot of libraries
The throw keyword
The throw statement allows you to create a custom error.
The throw statement is used together with an exception class. There are many exception classes
available in C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeException,
TimeOutException, etc:
public void checkAge(int age)
{
if (age < 18)
static void Main(string[] args)
{
{
throw new ArithmeticException("Access denied - You
checkAge(15);
must be at least 18 years old.");
}
}
else
{
Console.WriteLine("Access granted - You are old enough!");
}}
Difference
Debugging
Debugging is the process of finding errors during
application execution. It does not mean syntax
errors, with which the application cannot be
compiled, but on logic errors.