0% found this document useful (0 votes)
6 views29 pages

Chapter 4 WP With C# Exception Handling Student 1.0

b

Uploaded by

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

Chapter 4 WP With C# Exception Handling Student 1.0

b

Uploaded by

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

CHAPTER-4

C# EXCEPTION HANDLING
12/26/2024 ANDARGACHEW A. 1
CONTENTS
1. Introduction
2. Exception Handling
3. Exception classes in C#
4. User defined Exception
5. Benefits of Exceptions

12/26/2024 ANDARGACHEW A. 2
12/26/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.

12/26/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
12/26/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.

12/26/2024 ANDARGACHEW A. 6
HOW DO EXCEPTIONS
HANDLING WORK?

12/26/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.

12/26/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.

12/26/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.
}
12/26/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
12/26/2024 ANDARGACHEW A. 11
There are another Exception classes in C#, search about them !!

12/26/2024 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.
12/26/2024 ANDARGACHEW A. 13
EXAMPLE 1:

12/26/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?
12/26/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.
12/26/2024 ANDARGACHEW A. 16
EXERCISE 1:
Is the following code legal?

12/26/2024 ANDARGACHEW A. 17
EXERCISE 2:
What exception types can be caught by the
following handler?

What is wrong with using this type of exception


handler?
12/26/2024 ANDARGACHEW A. 18
EXERCISE 3: ORDER OF
EXCEPTION (A) (B)

void function1() void function1()


{ {
try try
{
{
// code
// code }
} catch(Exception1 ex)
catch(Exception ex) {
{ }
} catch(Exception ex)
catch(Exception1 ex) {
{ }
}
// if no rethrow occurs
}
// execution resumes here
}
12/26/2024 ANDARGACHEW A. 19
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)

12/26/2024 ANDARGACHEW A. 20
EXAMPLE 2:

if(value<0)
throw new NegativeNumberException(" Use Only
Positive numbers");

12/26/2024 ANDARGACHEW A. 21
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.
12/26/2024 ANDARGACHEW A. 22
EXERCISE 4: ADDING
EXCEPTIONS-1
This program is throwing
exception IndexOutOfRangeException.

12/26/2024 ANDARGACHEW A. 23
EXERCISE 5: ADDING
EXCEPTIONS-2
The given program is throwing
OverflowException

12/26/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

12/26/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".

12/26/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 intssssssaaaeger 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)
12/26/2024 ANDARGACHEW A. 27
Questions?

12/26/2024 ANDARGACHEW A. 28
Thank You
12/26/2024 ANDARGACHEW A. 29

You might also like