Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Exception Handling in C#

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 42

1

CHAPTER 5
C#
EXCEPTION HANDLING

01/24/2021 Exception Handling in C#


Contents
2

1. Introduction
2. Exception Handling
3. Exception classes in C#
4. User defined Exception
5. Benefits of Exceptions

01/24/2021
Introduction
3

 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.

01/24/2021
Exception
4

 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, such
as an attempt to divide by zero.
 Exceptions provide a way to transfer control
from one part of a program to another

01/24/2021
5

 Exception in .NET is an object, which signals an error


or an event, which is not anticipated in the normal
program flow.
 When such unusual event takes place, the executing method
’throws' a special object containing information about the
type of the error, the place in the program where the
error occurred as well as the program state at the
moment of the error.
 Each exception in .NET contains the so-called stack
trace, which gives information of where exactly the
error occurred.
01/24/2021
Exception Handling
6

 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.

01/24/2021
How Do Exceptions Handling Work?
7

 The exception handling mechanism follows a reversed


process.
1. When an exception is thrown, CLR begins searching an
exception handler in the callstack starting from the method
that has thrown the exception.
2. This is repeated for each of the methods down the call-stack
until a handler is found which catches the exception.
3. If Main(…) is reached and no handler is found, CLR
catches the exception and usually displays an error
message (either in the console or in a special error dialog
box).

01/24/2021
8

01/24/2021
9

 C# exception handling is built upon four keywords:


1. 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.
2. 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.

01/24/2021
10

3. finally: The finally block is used to execute a given


set of statements, whether an exception is thrown
or not thrown.
 Forexample, if you open a file, it must be closed whether
an exception is raised or not.
4. throw: A program throws an exception when a
problem shows up. This is done using a throw
keyword.

01/24/2021
11

 try block
 A try block contains code that requires common cleanup or
exception-recovery operations.
 The cleanup code should be put in a single finally block.
 The exception recovery code should be put in one or more
catch blocks.
 Create one catch block for each kind of type you want to
handle.
 A try block must have at least one catch or finally block.

01/24/2021
12

 catch block
 A catch block contains code to execute in response to an

exception.
 If the code in a try block doesn’t cause an exception to be thrown,
the CLR will never execute the code in any of its catch blocks.
 You may or may not specify a catch type in parenthesis after catch :
 The catch type must be of type System.Exception or a type that derived
from System.Exception
 If there is no catch type specified, that catch block handles any exception.
This is equivalent to having a catch block that specifies System.Exception
as a catch type.

01/24/2021
13

 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
 In choices 1-2, an exception is thrown and code starts looking
for a catch block whose type matches the exception thrown
 In choice 3, the finally block is executed
 You can also specify a variable name like catch(Exception e)
to access information specific to the exception.
01/24/2021
14

 finally block
 C# provides the finally block, which is guaranteed to
execute regardless of whether an exception occurs.
 If the try block executes without throwing, the finally
block executes.
 If the try block throws an exception, the finally block still
executes regardless of whether the exception is caught.
 This makes the finally block ideal to release resources
from the corresponding try block.

01/24/2021
15

 Local variables in a try block cannot be accessed in


the corresponding finally block, so variables that must
be accessed in both should be declared before the try
block.
 Placing the finally block before a catch block is a
syntax error.
 A try block does not require a finally block, sometimes
no clean-up is needed.
 A try block can have no more than one finally block.

01/24/2021
Syntax
16

 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.

01/24/2021
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
17
// within the try block. This code ALWAYS executes.
01/24/2021
}
Exception Classes in C#
18

 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.

01/24/2021
19

 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.

01/24/2021
20

There are another Exception classes in C#, search about them !!


01/24/2021
System.Exception properties
21

 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.
 When an exception occurs, a programmer might use a
different error message or indicate a new exception
type.
 The original exception object is stored in the InnerException
property.
01/24/2021
22

 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.

01/24/2021
Example 1:
23

01/24/2021
Example 2:
24

01/24/2021
Choosing the Exception to throw
25

 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?
01/24/2021
Do not catch everything?
26

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.
01/24/2021
Array in C#
27

 Declaring an Array
 int [] my_array= new int[size];
 Array initialization
 int [] my_array= {1,2,3,4};
 Access to the elements of an Array
 We access the array elements directly using their
indices. (0 to size-1)
 My_array[index]=100;

01/24/2021
Exercise 1:
28

Use
IndexOutOfRangeException
&
FormatException
&
Exception
01/24/2021
User Defined Exceptions
29

 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)

01/24/2021
Example 2:
30

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

01/24/2021
Benefits of Exceptions
31

 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

01/24/2021
32

 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.
 The caller could ignore the error returned by a
Win32 API, now the caller cannot continue with
exceptions. If the application cannot handle the
exception, CLR can terminate the application.

01/24/2021
Exercise 3:
33

 Is the following code legal?

01/24/2021
Exercise 4:
34

 What exception types can be caught by the


following handler?

 What is wrong with using this type of exception


handler?

01/24/2021
Exercise 5: Order of Exception
35

(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 her
}
01/24/2021
Exercise 6: Adding Exceptions-1
36

 This program is throwing


exception IndexOutOfRangeException.

01/24/2021
Exercise 7: Adding Exceptions-2
37

 The given program is throwing


OverflowException

01/24/2021
Exercise 8: FormatExceptions
38

 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

01/24/2021
Exercise 9: User defined Exception-1
39

 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".

01/24/2021
Exercise 10: User defined Exception-2
40

 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)

01/24/2021
41

Questions?
01/24/2021
42

Thank You
01/24/2021

You might also like