KEMBAR78
Chapter 4-Exception Handling | PDF | C Sharp (Programming Language) | Computer Programming
0% found this document useful (0 votes)
5 views23 pages

Chapter 4-Exception Handling

C# Exception Handling

Uploaded by

hello12001000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views23 pages

Chapter 4-Exception Handling

C# Exception Handling

Uploaded by

hello12001000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Department of Computer Science

Event- riven Programming (C#)

Chapter Four:
Exception Handling in C#
Contents

 Introducing Exception Handling

 Structured Exception Handling

 Implementing Exception Handling

09/22/2025
Introducing Exception Handling

 An exception is an unwanted or unexpected event, which occurs during the execution of

a program i.e., at runtime, that disrupts the normal flow of the program’s instructions.

 Sometimes during the execution of program, the user may face the possibility that the

program may crash or show an unexpected event during its runtime execution.

 This unwanted event is known as Exception and is generally gives the indication

regarding something wrong within the code.

09/22/2025
Introducing Exception Handling…

 A C# exception is a response to an exceptional circumstance that arises while a program

is running, such as an attempt to divide by zero.


 C# .NET includes built-in exception classes for every possible error.

 The Exception class is the base class of all the exception classes.

 Exceptions provide a way to transfer control from one part of a program to another.

09/22/2025
Introducing Exception Handling…

 C# exception handling is built upon four keywords: try, catch, finally, and throw.

 try: A try block identifies a block of code for which particular exceptions is
activated.
 It is followed by one or more catch blocks.
 Any suspected code that may raise exceptions should be put inside a try{ } block.
• During the execution, if an exception occurs, the flow of the control jumps to the
first matching catch block.

09/22/2025
Introducing Exception Handling…

 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. The catch block is an
exception handler block where you can perform some action such as logging and
auditing an exception.
 The catch block takes a parameter of an exception type using which you can get the
details of an exception.

09/22/2025
Introducing Exception Handling…

 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.
 The finally block will always be executed whether an exception raised or not. Usually, a
finally block should be used to release resources, e.g., to close any stream or file objects that
were opened in the try block.
 throw: A program throws an exception when a problem shows up. This is done using a

throw keyword.

09/22/2025
Introducing Exception Handling…

try
Syntax {
// statements causing exception
 Assuming a block raises an exception, a }
catch (ExceptionName e1)
method catches an exception using a {
// error handling code
combination of the try and catch keywords. }
catch (ExceptionName e2)
 A try/catch block is placed around the code {
// error handling code
that might generate an exception. }
catch (ExceptionName eN)
 Code within a try/catch block is referred to {
// error handling code
as protected code, and the syntax for using }
finally
try/catch looks like the following: {
// statements to be executed
}
09/22/2025
Introducing Exception Handling…

// C# program to illustrate the exception


Moreover, Exceptions are: using System;
namespace Exception {
 Runtime errors that disrupt normal
class Program {
static void Main(string[] args) {
program flow // taking two integer value
int A = 12;
 Objects that contain error details
int B = 0;
// divide by zero error
 Part of error handling mechanism
int c = A / B;
Console.Write("Value of C is " + c);
}
}
}

09/22/2025
Structured Exception Handling

 Exception Handling gives a way to control runtime programming error in a structured

and controlled manner.


 If any runtime error appears the handler shows easy and readable message telling user

what the problem is and continue the program.

09/22/2025
Structured Exception Handling

Exception Hierarchy (Exception classes)


 There are different kinds of exceptions which can be generated in C# program:
 Divide By Zero exception: It occurs when the user attempts to divide by zero
 Out of Memory exceptions: It occurs when then the program tries to use excessive
memory
 Index out of bound Exception: Accessing the array element or index which is not present
in it.
 Stackoverflow Exception: Mainly caused due to infinite recursion process

09/22/2025
Structured Exception Handling

Null Reference Exception : Occurs when the user attempts to reference an object

which is of NULL type.


…..and many more.

09/22/2025
Structured Exception Handling…

 In slide 15 diagram, all the exceptions are derived from the base class Exception which

gets further divided into two branches as ApplicationException and SystemException.


 SystemException is a base class for all CLR or program code generated errors or all
the built-in exception classes in .NET Framework.
 ApplicationException is a base class for all application related exceptions or all your
custom exceptions classes.

09/22/2025
Structured Exception Handling…

 All the exception classes are directly or indirectly derived from the Exception class.

 In case of ApplicationException, the user may create its own exception types and

classes.
 But SystemException contains all the known exception types such as
DivideByZeroException or NullReferenceException etc.

09/22/2025
Structured Exception Handling…

09/22/2025
Structured Exception Handling…

Exception Handling Best Practices


 Guidelines:

 Handle specific exceptions before


general ones
 Only catch exceptions you can handle
 Don't use exceptions for flow control
 Always clean up resources
 Include meaningful exception
messages
09/22/2025
Implementing Exception Handling

Difference between Errors and Exception


Errors:
 Errors are unexpected issues that may arise during computer program execution.

 Errors cannot be handled.

 All Errors are exceptions.

Exceptions:
 Exceptions are unexpected events that may arise during run-time.

 Exceptions can be handled using try-catch mechanisms.

 All exceptions are not errors.


09/22/2025
Implementing Exception Handling…

Properties of the Exception Class: The Exception class has many properties which help
the user to get information about the exception during exception.
 Data: This property helps to get the information about the arbitrary data which is held

by the property in the key-value pairs.


 TargetSite: This property helps to get the name of the method where the exception will

throw.
 Message: This property helps to provide the details about the main cause of the

exception occurrence.

09/22/2025
Implementing Exception Handling…

 HelpLink: This property helps to hold the URL for a particular exception.

 StackTrace: This property helps to provide the information about where the error

occurred.
 InnerException: This property helps to provide the information about the series of

exceptions that might have occurred.

09/22/2025
Implementing Exception Handling…

//C# program to demonstrate


NullReferenceException Console.WriteLine(length);
using System; Console.ReadLine();
}
namespace Null_Reference_Exception }
}
{
class Program
{
static void Main(string[] args)
{
string text = null;
int length = text.Length;

09/22/2025
Implementing Exception Handling…

//C# program to demonstrate


catch (NullReferenceException nex)
NullReferenceException solution
{
using System; Console.WriteLine(nex.Message);
namespace Null_Reference_Exception_Solve{ }
class Program { Console.ReadLine();
static void Main(string[] args) { }
string text = null; }
try { }
int length = text.Length;
Console.WriteLine(length);
Console.ReadLine();
}
09/22/2025
Implementing Exception Handling…

// C# program to demonstrate 'throwing for (int i = 0; i <= 5; i++)


exception IndexOutOfRangeException'. {
using System;
namespace IndexOutOfRangeException { Console.WriteLine(list[i].ToString());
class Program { }
static void Main(string[] args) { Console.ReadLine();
string[] list = new string[5]; }
list[0] = "Sunday"; }
list[1] = "Monday"; }
list[2] = "Tuesday";
list[3] = "Wednesday";
list[4] = "Thursday";

09/22/2025
Implementing Exception Handling…

// C# program to demonstrate 'throwing exception Console.WriteLine(list[i].ToString());


IndexOutOfRangeException’ solution. } }
catch (IndexOutOfRangeException ex) {
using System;
Console.WriteLine("An IndexOutOfRangeException occurred: "
namespace IndexOutOfRangeException_Solve { + ex.Message);
class Program { Console.WriteLine("Please ensure the loop index stays within the
array bounds.");
static void Main(string[] args) {
}
string[] list = new string[5]; catch (Exception ex) {
list[0] = "Sunday"; Console.WriteLine("An unexpected exception occurred: " +
ex.Message);
list[1] = "Monday";
}
list[2] = "Tuesday"; Console.ReadLine(); } }}
list[3] = "Wednesday";
list[4] = "Thursday";
try { for (int i = 0; i <= 5; i++) {

09/22/2025

You might also like