Computer Programming
Exception Handling ||
: Exception handling
Ms. Nausheeda B S
Mahmoud Rafeek Alfarra
Contents
What is an exception error?
Exception handling
Syntax
Exception Classes in C#
Example
Practices
User defined Exception
2
What is an exception error?
An exception is a problem that arises
during the execution of a program.
A C# exception is a response to an
exceptional situation that arises while a
program is running, such as an attempt to
divide by zero.
3
What is an exception error?
Exceptions provide a way to transfer
control from one part of a program to
another.
4
Exception handling
C# exception handling is built upon four
keywords:
try: A try block identifies a block of code for
which particular exceptions will be activated.
It's followed by one or more catch blocks.
catch: A program catches an exception with
an exception handler at the place in a
program where you want to handle the
problem. The catch keyword indicates the
catching of an exception.
5
Exception handling
C# exception handling is built upon four
keywords:
finally: The finally block is used to execute a
given set of statements, whether an exception
is thrown or not thrown.
For example, if you open a file, it must be closed
whether an exception is raised or not.
throw: A program throws an exception when
a problem shows up. This is done using a
throw keyword.
6
Syntax
Assuming a block will raise and exception,
a method catches an exception using a
combination of the try and catch keywords.
You can list down multiple catch
statements to catch different type of
exceptions in case your try block raises
more than one exception in different
situations.
7
Syntax
8
Syntax
C# exceptions are represented by classes.
The exception classes in C# are mainly
directly or indirectly derived from the
System.Exception class.
Some of the exception classes derived
from the System.
Exception class are the System.ApplicationException
and System.SystemException classes.
9
Syntax
The System.ApplicationException class
supports exceptions generated by
application programs.
So the exceptions defined by the
programmers should derive from this
class.
The System.SystemException class is
the base class for all predefined system
exception.
10
Hierarchy of Exceptions
11
Exception Classes in C#
There are another Exception classes in C#, search about them !!
12
Example 1
class Program {
public static void division(int num1, int num2)
{
float result=0.0f;
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception Error !! \n divid by zero !!");
// Console.WriteLine("Exception caught: {0}", e);
}
finally
{
Console.WriteLine("Result: {0} ", result);
}
}
static void Main(string[] args)
{
division(10,0);
Console.ReadLine();
} } 13
Example 2
catch (DivideByZeroException ex2) Try
{ ex1.Message
// ….. Try
} Exception only
catch (FormatException ex1) Instead of
{ DivideByZeroException
Or
//……
FormatException
}
14
Practice
Use
IndexOutOfRangeException
&
FormatException
&
Exception
15
public class Student
{
public string StudentName { get; set; }
}
public class Program
{
public static void Main(String[] args)
{
Student std = null;
try
{
PrintStudentName(std);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message );
} 16
public static void PrintStudentName( Student std)
{
if (std == null)
throw new NullReferenceException("Student
object is null. ");
Console.WriteLine(std.StudentName);
}
17
Throwing our own Exceptions
◦ We can throw our own exceptions.
◦ But Exception must be the ultimate base class for all exceptions in C#.
◦ So the user-defined exception classes must inherit from either Exception
class or one of its standard derived classes.
◦ We can do this by using the keyword throw as follows.
Throw new Throwable_Subclass;
Examples:
throw new ArithmeticException();
throw new FormatException();
you can also define your own exception.
◦ User defined exception classes are derived from the ApplicationException
class. 18
User Defined Exception
Every user defined
exception must be
derived from ApplicationException
ApplicationException
Every user
defined
exception New Exception
must be Class
defined as a
new class
19
User Defined Exception
using System;
namespace ExceptionHandling
{
class NegativeNumberException:Exception
{
public NegativeNumberException(string message)
// show message
}
}
if(value<0)
throw new NegativeNumberException(" Use Only Positive numbers");
catch(NegativeNumberException e)
{
}
20
Best Practices
◦ catch blocks should begin with the exceptions lowest in the
hierarchy and continue with the more general exceptions
◦ Otherwise a compilation error will occur
◦ Each catch block should handle only these exceptions which it
expects
◦ Handling all exception disregarding their type is popular
bad practice!
◦ When raising an exception always pass to the constructor good
explanation message
21
Exceptions can decrease the application performance
◦ Throw exceptions only in situations which are really exceptional
and should be handled
◦ Do not throw exceptions in the normal program control flow
(e.g.: on invalid user input)
◦ Some exceptions can be thrown at any time with no
way to predict them, System.OutOfMemoryException
22
Write a C# program that prompts the user to input two numbers and
divides them. Handle an exception when the user enters non-numeric
values.
23
using System;
class Program
{
static void Main(String[] args) {
try {
Console.Write("Input the first number: ");
string inp1 = Console.ReadLine();
double number1 = Convert.ToDouble(inp1);
Console.Write("Input the second number: ");
//string inp2 = Console.ReadLine();
//double number2 = Convert.ToDouble(inp2);
double number2 = Convert.ToDouble(Console.ReadLine());
if (number2 != 0) {
double result = number1 / number2;
Console.WriteLine("Result: " + result);
} else {
Console.WriteLine("Error: Cannot divide by zero.");
}
24
}
catch (FormatException) {
Console.WriteLine("Error: Non-numeric value entered.");
} catch (Exception ex) {
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
Write a C# program to implement a method that takes an integer as input and
throws an exception if the number is negative. Handle the exception in the
calling code.
25
using System;
class Program {
static void ValidateNumber(int number) {
if (number < 0) {
throw new NegativeNumberException("Negative number not allowed.");
}
}
static void Main(String[] args) {
try {
Console.Write("Input an integer: ");
int number = Convert.ToInt32(Console.ReadLine());
ValidateNumber(number);
Console.WriteLine("Valid input: " + number);
}
catch (NegativeNumberException ex) {
Console.WriteLine("Error: " + ex.Message);
} 22
catch (FormatException) {
Console.WriteLine("Error: Invalid input. Please enter an integer.");
}
catch (Exception ex) {
Console.WriteLine("An error occurred: " + ex.Message);
}
class NegativeNumberException: Exception {
public NegativeNumberException(string message): base(message) { }
}
27
using System;
class Program {
static void checkAge(int age)
{
if (age < 18) {
throw new ArithmeticException("Access denied, age must be 18 or more ");
}
else {
Console.WriteLine("Access granted - You are old enough!");
}
}
static void Main(string[] args) {
try {
int age;
Console.WriteLine("enter age");
age=Convert.ToInt32(Console.ReadLine());
checkAge(age);
} 24
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
29
Write a C# program that prompts the user to
input a numeric integer and throws an exception
if the number is less than 0 or greater than
1000.
30
using System;
class NumberOutofRangeException: Exception {
public NumberOutofRangeException(string message): base(message) { }
}
class Program {
static void ValidateNumber(int number) {
if (number < 0 || number>1000) {
throw new NumberOutofRangeException("Number between 0 and 1000.");
}
}
static void Main(String[] args) {
try {
Console.Write("Input an integer: ");
31
int number = Convert.ToInt32(Console.ReadLine());
ValidateNumber(number);
Console.WriteLine("Valid input: " + number);
}
catch (NumberOutofRangeException ex) {
Console.WriteLine("Error: " + ex.Message);
}
catch (FormatException) {
Console.WriteLine("Error: Invalid input. Please enter an integer.");
}
catch (Exception ex) {
Console.WriteLine("An error occurred: " + ex.Message);
}
22
Mahmoud Rafeek Alfarra