Chapter 3 - Exception Handling
Chapter 3 - Exception Handling
Chapter 3:
Exception Handling
C# by Dagne w 2
Exception Handling
Exception Handling
An exception is unforeseen error that occur when a
program is running.
Examples:
trying to read from a file that does not exist, throws
FileNotFoundException.
Trying to read from a database table that does not exist,
throws a SqlException.
Showing actual unhandled exceptions to the end user is
bad for two reasons 1. Users will be annoyed as they are
cryptic and does not make much sense to the end users. 2.
Exceptions contain information, that can be used for
hacking
C# by Dagne w 3
Exception Handling Keywords
The exception handling in c# is one of the
powerful mechanism to handle the runtime
errors such as ClassNotFound, IO, SQL, Remote etc.
There are 5 keywords used in C# exception handling.
• try
• catch
• finally
• throw
• throws
C# by Dagne w 5
Exception handling
C# by Dagne w 6
c# Exception Handling …
using System;
public class ExExample
{
public static void Main(string[] args)
{
try
{
int a = 10;
int b = 0;
int x = a / b;
}
catch (Exception e) { Console.WriteLine(e); }
finally { Console.WriteLine("Finally block is executed"); }
Console.WriteLine("Rest of the code");
}
}
C# by Dagne w 7
Exception
C# Checked and Unchecked
C# provides checked and unchecked keyword to
handle integral type exceptions. Checked and
unchecked keywords specify checked context and
unchecked context respectively. In checked context,
arithmetic overflow raises an exception whereas, in an
unchecked context, arithmetic overflow is ignored and
result is truncated.
C# Checked
The checked keyword is used to explicitly check
overflow and conversion of integral type values at
compile time.
.
C# by Dagne w 8
C# System Exception class
C# by Dagne w 9
Checked Exceptions
The classes that extend Throwable class except
RuntimeException and Error are known as
checked exceptions
Example.IOException, SQLException etc.
Checked exceptions are checked at compile-time.
C# by Dagne w 10
Unchecked Exception
C# by Dagne w 11
Error Exceptions
C# by Dagne w 12
THANK YOU!!
C# by Dagne w 13