SlideShare a Scribd company logo
11/14/2024 ANDARGACHEW A. 1
CHAPTER-4
C# EXCEPTION HANDLING
11/14/2024 ANDARGACHEW A. 2
CONTENTS
1. Introduction
2. Exception Handling
3. Exception classes in C#
4. User defined Exception
5. Benefits of Exceptions
11/14/2024 ANDARGACHEW A. 3
INTRODUCTION
There are three categories of errors:
Syntax errors arise because the rules of the language have not
been followed. They are detected by the compiler.
Runtime errors occur while the program is running if the
environment detects an operation that is impossible to carry out.
Logical errors occur when a program doesn't perform the way it
was intended to.
11/14/2024 ANDARGACHEW A. 4
EXCEPTION
An Exception
It 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 [provide a way to transfer control from one
part of a program to another]
Each exception in .NET contains the so-called stack trace,
which gives information about
The type of the error,
The place in the program where the error occurred
The program state at the moment of the error
11/14/2024 ANDARGACHEW A. 5
EXCEPTION HANDLING
Exception handling is a mechanism, which allows
exceptions to be thrown and caught.
This mechanism is provided internally by the CLR (Common
Language Runtime).
Parts of the exception handling infrastructure are the language
constructs in C# for throwing and catching exceptions.
CLR takes care to propagate each exception to the code that can
handle it.
11/14/2024 ANDARGACHEW A. 6
HOW DO EXCEPTIONS HANDLING WORK?
11/14/2024 ANDARGACHEW A. 7
C# exception handling is built upon four keywords:
1. try: a block of code for which particular exceptions will be
activated.
2. catch: an exception handler block where you can perform
some action such as logging and auditing an exception.
3. finally: used to execute a given set of statements, whether
an exception is thrown or not thrown.
4. throw: A program throws an exception when a problem shows
up. This is done using a throw keyword.
11/14/2024 ANDARGACHEW A. 8
Important points
A try block must have at least one catch or finally block.
 A try block does not require a finally block, sometimes no clean-up is needed.
Once the catch block that matches the exception is found, you have 3
choices:
1. Re-throw the same exception, notifying the higher-up call stack of the exception
2. Throw a different exception, giving richer exception information to code higher-up in
the call stack
3. Let the code continue from the bottom of the catch block
Local variables in a try block cannot be accessed in the corresponding
finally block
Placing the finally block before a catch block is a syntax error.
11/14/2024 ANDARGACHEW A. 9
SYNTAX
try {
// code that requires common cleanup or
// exception-recovery operations
}
catch (InvalidOperationException) {
//code that recovers from an InvalidOperationException
// (or any exception type derived from it)
}
catch (SomeOtherException) {
// code that recovers from an SomeOtherException
// (or any exception type derived from it)
}
catch {
// code that recovers from any kind of exception
// when you catch any exception, you usually re-throw
throw;
}
finally {
// code that cleans up any operations started
// within the try block. This code ALWAYS executes.
}
11/14/2024 ANDARGACHEW A. 10
EXCEPTION CLASSES IN C#
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
System.ApplicationException and
System.SystemException
11/14/2024 11
There are another Exception classes in C#, search about them !!
11/14/2024 ANDARGACHEW A. 12
SYSTEM.EXCEPTION PROPERTIES
Class Exception’s properties are used to formulate error
messages indicating a caught exception.
Property Message stores the error message associated with an Exception
object.
Property StackTrace contains a string that represents the method-call stack.
Other properties:
HelpLink specifies the location of a help file that describes the problem.
Source specifies the name of the application or object that caused the
exception.
TargetSite specifies the method where the exception originated.
11/14/2024 ANDARGACHEW A. 13
EXAMPLE 1:
11/14/2024 ANDARGACHEW A. 14
CHOOSING THE EXCEPTION TO THROW
When implementing your own methods, you should throw
an exception when the method cannot complete its task.
Associating each type of malfunction with an
appropriately named exception class improves program
clarity.
1. What Exception-derived type are you going to throw?
2. What string message are you going to pass to the exception
type’s constructor?
11/14/2024 ANDARGACHEW A. 15
DO NOT CATCH EVERYTHING?
try {
// code that might fail…
}
catch (Exception) {
…
}
How can you write code that can recover from all situations???
A class library should never ever swallow all exceptions. The
application should get a chance to handle the exception.
You can catch all exceptions only if you are going to process it and
re-throw it again.
11/14/2024 ANDARGACHEW A. 16
USER DEFINED EXCEPTIONS
User-defined exception classes should derive directly or indirectly from class
Exception of namespace System.
Exceptions should be documented so that other developers will know how to
handle them.
User-defined exceptions should define three constructors:
A parameterless constructor
A constructor that receives a string argument
(the error message)
A constructor that receives a string argument and an Exception argument (the
error message and the inner exception object)
11/14/2024 ANDARGACHEW A. 17
EXAMPLE 2:
if(value<0)
throw new NegativeNumberException(" Use Only Positive numbers");
11/14/2024 ANDARGACHEW A. 18
BENEFITS OF EXCEPTIONS

The ability to keep cleanup code in a dedicated location and making sure this
cleanup code will execute

The ability to keep code that deals with exceptional situations in a central
place

The ability to locate and fix bugs in the code

Unified error handling: all .NET Framework classes throw exceptions to handle
error cases

Exceptions also include a stack trace that tells you the path application took
until the error occurred.

You can also put any information you want in a user-defined exception of your
own.
11/14/2024 ANDARGACHEW A. 19
EXERCISE 1:
Is the following code legal?
11/14/2024 ANDARGACHEW A. 20
EXERCISE 2:
What exception types can be caught by the following
handler?
What is wrong with using this type of exception handler?
11/14/2024 ANDARGACHEW A. 21
EXERCISE 3: ORDER OF EXCEPTION
void function1()
{
try
{
// code
}
catch(Exception1 ex)
{
}
catch(Exception ex)
{
}
// if no rethrow occurs
// execution resumes here
}
void function1()
{
try
{
// code
}
catch(Exception ex)
{
}
catch(Exception1 ex)
{
}
}
(A) (B)
11/14/2024 ANDARGACHEW A. 22
EXERCISE 4: ADDING EXCEPTIONS-1
This program is throwing
exception IndexOutOfRangeException.
11/14/2024 ANDARGACHEW A. 23
EXERCISE 5: ADDING EXCEPTIONS-2
The given program is throwing OverflowException
11/14/2024 ANDARGACHEW A. 24
EXERCISE 6: FORMATEXCEPTIONS
Create a program that inputs miles driven and
gallons used, and calculates miles per gallon.
The example should use exception handling to process the
FormatExceptions that occur when converting the input strings to
doubles. If invalid data is entered, display a message informing
the user
11/14/2024 ANDARGACHEW A. 25
EXERCISE 7: USER DEFINED EXCEPTION-1
Write a program that takes a positive integer from the
console and prints the square root of this integer. If the
input is negative or invalid print "Invalid Number" in the
console. In all cases print "Good Bye".
11/14/2024 ANDARGACHEW A. 26
EXERCISE 8: USER DEFINED EXCEPTION-2
Write a method ReadNumber(int start, int end) that reads
an integer from the console in the range [start…end].
In case the input integer is not valid or it is not in the required
range throw appropriate exception.
Using this method, write a program that takes 10 integers a1, a2,
…, a10 such that 1 < a1 < … < a10 < 100.
(When invalid number is used we can throw Exception because there is no other
exception that can better describe the problem. As an alternative we can define our
own exception class called in a way that better describes the problem, e.g.
InvalidNumberException)
11/14/2024 ANDARGACHEW A. 27
Questions?
11/14/2024 ANDARGACHEW A. 28
Thank You

More Related Content

PPTX
12. Exception Handling
PPTX
Exception Handlin g C#.pptx
PPTX
6-Error Handling.pptx
PPT
12 Exceptions handling
PPT
C# Exceptions Handling
PPT
Exceptions
PPTX
Exceptions overview
PPT
Exceptions
12. Exception Handling
Exception Handlin g C#.pptx
6-Error Handling.pptx
12 Exceptions handling
C# Exceptions Handling
Exceptions
Exceptions overview
Exceptions

Similar to Chapter_4_WP_with_C#_Exception_Handling_student_1.0.pptx (20)

PPTX
PPTX
Exception guidelines in c#
PPTX
IakakkakjabbhjajjjjjajjajwsjException.pptx
PPTX
PPTX
Exception Handling in C#
PPTX
Exception handling in ASP .NET
PPTX
Lecture 3.1.1 Try Throw Catch.pptx
PPT
Excetion handling Software Engineering Units
PPTX
Exceptions in C++ Object Oriented Programming.pptx
PPTX
PDF
Design byexceptions
PPTX
Exception handling
PPTX
What is Exception Handling?
PDF
22 scheme OOPs with C++ BCS306B_module5.pdf
PPT
Exception handling
PPTX
Implicit and explicit sequence control with exception handling
PPT
Exception
PPTX
Exceptions
PPTX
Exceptions
PPTX
Lecture 1 Try Throw Catch.pptx
Exception guidelines in c#
IakakkakjabbhjajjjjjajjajwsjException.pptx
Exception Handling in C#
Exception handling in ASP .NET
Lecture 3.1.1 Try Throw Catch.pptx
Excetion handling Software Engineering Units
Exceptions in C++ Object Oriented Programming.pptx
Design byexceptions
Exception handling
What is Exception Handling?
22 scheme OOPs with C++ BCS306B_module5.pdf
Exception handling
Implicit and explicit sequence control with exception handling
Exception
Exceptions
Exceptions
Lecture 1 Try Throw Catch.pptx
Ad

Recently uploaded (20)

PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
Well-logging-methods_new................
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PPTX
Fundamentals of Mechanical Engineering.pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PPT
Mechanical Engineering MATERIALS Selection
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
III.4.1.2_The_Space_Environment.p pdffdf
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
Safety Seminar civil to be ensured for safe working.
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
A SYSTEMATIC REVIEW OF APPLICATIONS IN FRAUD DETECTION
PPT
introduction to datamining and warehousing
PDF
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Well-logging-methods_new................
Categorization of Factors Affecting Classification Algorithms Selection
Fundamentals of Mechanical Engineering.pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
Mechanical Engineering MATERIALS Selection
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Foundation to blockchain - A guide to Blockchain Tech
Automation-in-Manufacturing-Chapter-Introduction.pdf
III.4.1.2_The_Space_Environment.p pdffdf
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Safety Seminar civil to be ensured for safe working.
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
A SYSTEMATIC REVIEW OF APPLICATIONS IN FRAUD DETECTION
introduction to datamining and warehousing
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
Ad

Chapter_4_WP_with_C#_Exception_Handling_student_1.0.pptx

  • 1. 11/14/2024 ANDARGACHEW A. 1 CHAPTER-4 C# EXCEPTION HANDLING
  • 2. 11/14/2024 ANDARGACHEW A. 2 CONTENTS 1. Introduction 2. Exception Handling 3. Exception classes in C# 4. User defined Exception 5. Benefits of Exceptions
  • 3. 11/14/2024 ANDARGACHEW A. 3 INTRODUCTION There are three categories of errors: Syntax errors arise because the rules of the language have not been followed. They are detected by the compiler. Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out. Logical errors occur when a program doesn't perform the way it was intended to.
  • 4. 11/14/2024 ANDARGACHEW A. 4 EXCEPTION An Exception It 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 [provide a way to transfer control from one part of a program to another] Each exception in .NET contains the so-called stack trace, which gives information about The type of the error, The place in the program where the error occurred The program state at the moment of the error
  • 5. 11/14/2024 ANDARGACHEW A. 5 EXCEPTION HANDLING Exception handling is a mechanism, which allows exceptions to be thrown and caught. This mechanism is provided internally by the CLR (Common Language Runtime). Parts of the exception handling infrastructure are the language constructs in C# for throwing and catching exceptions. CLR takes care to propagate each exception to the code that can handle it.
  • 6. 11/14/2024 ANDARGACHEW A. 6 HOW DO EXCEPTIONS HANDLING WORK?
  • 7. 11/14/2024 ANDARGACHEW A. 7 C# exception handling is built upon four keywords: 1. try: a block of code for which particular exceptions will be activated. 2. catch: an exception handler block where you can perform some action such as logging and auditing an exception. 3. finally: used to execute a given set of statements, whether an exception is thrown or not thrown. 4. throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
  • 8. 11/14/2024 ANDARGACHEW A. 8 Important points A try block must have at least one catch or finally block.  A try block does not require a finally block, sometimes no clean-up is needed. Once the catch block that matches the exception is found, you have 3 choices: 1. Re-throw the same exception, notifying the higher-up call stack of the exception 2. Throw a different exception, giving richer exception information to code higher-up in the call stack 3. Let the code continue from the bottom of the catch block Local variables in a try block cannot be accessed in the corresponding finally block Placing the finally block before a catch block is a syntax error.
  • 9. 11/14/2024 ANDARGACHEW A. 9 SYNTAX try { // code that requires common cleanup or // exception-recovery operations } catch (InvalidOperationException) { //code that recovers from an InvalidOperationException // (or any exception type derived from it) } catch (SomeOtherException) { // code that recovers from an SomeOtherException // (or any exception type derived from it) } catch { // code that recovers from any kind of exception // when you catch any exception, you usually re-throw throw; } finally { // code that cleans up any operations started // within the try block. This code ALWAYS executes. }
  • 10. 11/14/2024 ANDARGACHEW A. 10 EXCEPTION CLASSES IN C# 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 System.ApplicationException and System.SystemException
  • 11. 11/14/2024 11 There are another Exception classes in C#, search about them !!
  • 12. 11/14/2024 ANDARGACHEW A. 12 SYSTEM.EXCEPTION PROPERTIES Class Exception’s properties are used to formulate error messages indicating a caught exception. Property Message stores the error message associated with an Exception object. Property StackTrace contains a string that represents the method-call stack. Other properties: HelpLink specifies the location of a help file that describes the problem. Source specifies the name of the application or object that caused the exception. TargetSite specifies the method where the exception originated.
  • 13. 11/14/2024 ANDARGACHEW A. 13 EXAMPLE 1:
  • 14. 11/14/2024 ANDARGACHEW A. 14 CHOOSING THE EXCEPTION TO THROW When implementing your own methods, you should throw an exception when the method cannot complete its task. Associating each type of malfunction with an appropriately named exception class improves program clarity. 1. What Exception-derived type are you going to throw? 2. What string message are you going to pass to the exception type’s constructor?
  • 15. 11/14/2024 ANDARGACHEW A. 15 DO NOT CATCH EVERYTHING? try { // code that might fail… } catch (Exception) { … } How can you write code that can recover from all situations??? A class library should never ever swallow all exceptions. The application should get a chance to handle the exception. You can catch all exceptions only if you are going to process it and re-throw it again.
  • 16. 11/14/2024 ANDARGACHEW A. 16 USER DEFINED EXCEPTIONS User-defined exception classes should derive directly or indirectly from class Exception of namespace System. Exceptions should be documented so that other developers will know how to handle them. User-defined exceptions should define three constructors: A parameterless constructor A constructor that receives a string argument (the error message) A constructor that receives a string argument and an Exception argument (the error message and the inner exception object)
  • 17. 11/14/2024 ANDARGACHEW A. 17 EXAMPLE 2: if(value<0) throw new NegativeNumberException(" Use Only Positive numbers");
  • 18. 11/14/2024 ANDARGACHEW A. 18 BENEFITS OF EXCEPTIONS  The ability to keep cleanup code in a dedicated location and making sure this cleanup code will execute  The ability to keep code that deals with exceptional situations in a central place  The ability to locate and fix bugs in the code  Unified error handling: all .NET Framework classes throw exceptions to handle error cases  Exceptions also include a stack trace that tells you the path application took until the error occurred.  You can also put any information you want in a user-defined exception of your own.
  • 19. 11/14/2024 ANDARGACHEW A. 19 EXERCISE 1: Is the following code legal?
  • 20. 11/14/2024 ANDARGACHEW A. 20 EXERCISE 2: What exception types can be caught by the following handler? What is wrong with using this type of exception handler?
  • 21. 11/14/2024 ANDARGACHEW A. 21 EXERCISE 3: ORDER OF EXCEPTION void function1() { try { // code } catch(Exception1 ex) { } catch(Exception ex) { } // if no rethrow occurs // execution resumes here } void function1() { try { // code } catch(Exception ex) { } catch(Exception1 ex) { } } (A) (B)
  • 22. 11/14/2024 ANDARGACHEW A. 22 EXERCISE 4: ADDING EXCEPTIONS-1 This program is throwing exception IndexOutOfRangeException.
  • 23. 11/14/2024 ANDARGACHEW A. 23 EXERCISE 5: ADDING EXCEPTIONS-2 The given program is throwing OverflowException
  • 24. 11/14/2024 ANDARGACHEW A. 24 EXERCISE 6: FORMATEXCEPTIONS Create a program that inputs miles driven and gallons used, and calculates miles per gallon. The example should use exception handling to process the FormatExceptions that occur when converting the input strings to doubles. If invalid data is entered, display a message informing the user
  • 25. 11/14/2024 ANDARGACHEW A. 25 EXERCISE 7: USER DEFINED EXCEPTION-1 Write a program that takes a positive integer from the console and prints the square root of this integer. If the input is negative or invalid print "Invalid Number" in the console. In all cases print "Good Bye".
  • 26. 11/14/2024 ANDARGACHEW A. 26 EXERCISE 8: USER DEFINED EXCEPTION-2 Write a method ReadNumber(int start, int end) that reads an integer from the console in the range [start…end]. In case the input integer is not valid or it is not in the required range throw appropriate exception. Using this method, write a program that takes 10 integers a1, a2, …, a10 such that 1 < a1 < … < a10 < 100. (When invalid number is used we can throw Exception because there is no other exception that can better describe the problem. As an alternative we can define our own exception class called in a way that better describes the problem, e.g. InvalidNumberException)
  • 27. 11/14/2024 ANDARGACHEW A. 27 Questions?