0% found this document useful (0 votes)
11 views30 pages

Chapter Four Slide C# STD

This document discusses exception handling in the .NET framework and C#. It introduces exceptions as notifications that interrupt normal program execution. Exceptions provide a way to detect and react to unexpected events. The document explains how exceptions are thrown and caught, and the call stack mechanism used to find exception handlers. It provides examples of throwing exceptions and catching them in C#, as well as common exception classes like NullReferenceException and DivideByZeroException.

Uploaded by

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

Chapter Four Slide C# STD

This document discusses exception handling in the .NET framework and C#. It introduces exceptions as notifications that interrupt normal program execution. Exceptions provide a way to detect and react to unexpected events. The document explains how exceptions are thrown and caught, and the call stack mechanism used to find exception handlers. It provides examples of throwing exceptions and catching them in C#, as well as common exception classes like NullReferenceException and DivideByZeroException.

Uploaded by

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

Windows Programming

Chapter Four
Exception Handling in .NET Framework,
C#

1 Prepared by Tesfa K. 5/15/2022


 Main Points to be Discussed
 Introducing Exception and
exception Handling
 Implementing Exception
Handling

2 Prepared by Tesfa K. 5/15/2022


Exception in C#
 When we write a program, we describe step-by-step process - what
the computer must do and in most of the cases we trust that the
program will execute normally.
 Most of the time, programs are following the normal pattern, however
there is a situation that exceptions may occur.
 Let’s say we want to read a file and display its contents on the screen.
 Let’s assume that the file is located on a remote server and during
the process of reading it, the connection goes down.
 The file then will be only partially loaded.
 The program will not be able to execute normally and show file’s
contents on the screen.
 In this case, we have an exception from the normal (and correct)
program execution and this exception must be reported to the
user and/or the administrator.
3 Prepared by Tesfa K. 5/15/2022
Exception in C#...
 Exception:- is a notification that something interrupts the normal
program execution.
 Exceptions provide a programming paradigm for detecting and
reacting to unexpected events.
 When an exception arises, the state of the program is saved, the
normal flow is interrupted and the control is passed to an
exception handler.
 Exceptions are raised or thrown by programming code that must
send a signal to the executing program about an error or an unusual
situation.
 For example, if we try to open a file, which doesn’t exist, the code
responsible for opening the file will detect this and will throw an
exception with a proper error message.

4 Prepared by Tesfa K. 5/15/2022


Catching and Handling Exceptions
 Exception handling is a mechanism, which allows
exceptions to be thrown and caught.
 This mechanism is provided internally by the
CLR(Common Language Runtime).
 CLR takes care to propagate each exception to the
code that can handle it.

5 Prepared by Tesfa K. 5/15/2022


Throwing an Exception-Example

6 Prepared by Tesfa K. 5/15/2022


Example Description
 In the above example, the first two lines of ReadFile() contain code
that throws an exception.
 In this example, if the file WrongTextFile.txt doesn’t exist, the
constructor StreamReader(string, fileName) will throw a
FileNotFoundException.
 If an unexpected problem occurs during the input-output operations,
the stream methods, such as ReadLine() will throw an IOException.
 The code above will successfully compile because C# does not have
checked exceptions but at run-time it will throw an exception if the
WrongTextFile.txt file does not exist.
 The end result in this case is an error message displayed on the
console.
 The console output also contains information of where and how
the error occurred.
7 Prepared by Tesfa K. 5/15/2022
How Do Exceptions Work?
 If during the normal program execution one of the methods
throws an exception, the normal flow of the program is
interrupted.
 In the example above, this happens when the StreamReader
is initialized.
 Let’s take a look on the following line:
TextReader reader = new StreamReader("WrongTextFile.txt");
 If this line triggers an error, the reader local variable will not be
initialized and it will have its default value of null.
 None of the lines that follow in the method will be executed.
 The program will be interrupted until the CLR finds a handler
that can process the exception.

8 Prepared by Tesfa K. 5/15/2022


Catching Exceptions in C#
 After a method throws an exception, CLR is looking for an exception handler that
can process the error.
 To understand how this works, we will take a closer look on the concept of a call-
stack.
 The program call-stack is a stack structure that holds information about
method calls:- method local variables, method parameters, method names and likes
 .NET programs start from the Main(…) method, which is the entry point of the
program.
 Another method, let’s name it "Method 1" could be called from Main.
 Let "Method 1" call "Method 2" and so on until "Method N" is called.
 When "Method N" finishes, the program flow returns back to its calling method
(in our example it would be "Method N-1"), then back to its calling method and
so on.
 This goes on until the Main(…) method is reached. Once Main(…) finishes, the
entire program exits.
9 Prepared by Tesfa K. 5/15/2022
Catching Exceptions in C#...
 The general principle is that when a new method is called, it is pushed on top of
the stack.
 When the method finishes, it is pulled back from the stack.
 At any given point in time, the call-stack contains all the methods called during the
execution – from the starting method Main(…) to the last called method, which is
currently executing, along with their local variables and arguments taken as input.
 The exception handling mechanism follows a reversed process.
 When an exception is thrown, CLR begins searching an exception handler in the
call-stack starting from the method that has thrown the exception.
 This is repeated for each of the methods down the call-stack until a handler is
found which catches the exception.
 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).
10 Prepared by Tesfa K. 5/15/2022
Catching Exceptions in C#...
 The described method call and exception handling
process could be visualized in the following
diagram (steps 1 through 5):

11 Prepared by Tesfa K. 5/15/2022


C# Exception Handling
 It is the process to handle runtime errors.
 We perform exception handling so that normal flow of
the application can be maintained even after runtime
errors.
 All exceptions are derived from System.Exception class.
 If we don't handle the exception, it prints exception
message and terminates the program.
Advantage of Exception Handling
 It maintains the normal flow of the application.
 In such case, rest of the code is executed event after
exception.
12 Prepared by Tesfa K. 5/15/2022
Common Exceptions Example:
Exception Description

 System.DivideByZeroException  handles the error generated by


dividing a number with zero.

 System.NullReferenceException  handles the error generated by


referencing the null object.

 System.InvalidCastException  handles the error generated by


invalid typecasting.

 System.IO.IOException  handles the Input Output errors.


 System.FieldAccessException  handles the error generated by
invalid private or protected field
access.
13 Prepared by Tesfa K. 5/15/2022
Common Exceptions Example..
Exception Class Cause of Exception
• SystemException  A failed run time check; used as a base class for other
exceptions.
• AccessException  Failure to access a type member , such as a method or field.
• ArgumentException  An argument to a method was invalid.
• ArgumentNullException  A null argument was passed to a method that does not accept it.
• ArgumentOutOfRangeException Argument value is out of range.
• ArithmeticException  Arithmetic over or underflow has occurred.
• ArrayTypeMismatchException  Attempt to store the wrong type of object in an array.
• BadImageFormatException  Image is in wrong format
• CoreException  Base class for exceptions thrown by the runtime.
• FormatException  The format of an argument is wrong.
• IndexOutofRangeException  An Array index is out of range
• InvalidOperationException  A method was called at an invalid time
• MissingmemberException  An invalid version of a DLL was accessed
• NotFiniteException  A number is not valid
• NotSupportedException  Indicates that a method is not implemented by a class
• OutofmemoryException  Not enough memory to continue execution
• StackOverFlowException  A Stack has overflowed

14 Prepared by Tesfa K. 5/15/2022


C# Exception Handling Keywords
 In C#, we use 4 keywords to perform exception handling:
 try
 catch
 finally, and
 throw

15 Prepared by Tesfa K. 5/15/2022


The try-catch Programming Construct
 To handle an exception, we must surround the code that could throw
an exception with a try-catch block:
try
{
// Some code that may throw an exception
}
catch (ExceptionType objectName)
{
// Code handling an Exception
}

16 Prepared by Tesfa K. 5/15/2022


The try-catch Programming Construct
 The try-catch construct consists of one try block and one
or more catch blocks.
 Within the try block we put the code that could throw
exceptions.
 The ExceptionType in the catch block must be a type,
derived from System.Exception otherwise the code
wouldn’t compile.
 The expression within brackets after catch is also a
declaration of a variable:-thus inside the catch block we
can use objectName to use the properties of the
exception or call its methods.

17 Prepared by Tesfa K. 5/15/2022


Before exception is handled and after the exception is handled
1.using System;
1. using System;
2.public class ExExample
2. public class Example 3.{
3. { 4. public static void Main(string[] args)
4. public static void Main(string[] args)
5. {
6. try
5. { 7. {
6. int a = 10; 8. int a = 10;
7. int b = 0; 9. int b = 0;
10. int x = a / b;
8. int x = a/b;
11. }
9. Console.WriteLine("Rest of the code"); 12. catch (Exception e) {
10. } 13. Console.WriteLine(e);
11. } 14. }
15. Console.WriteLine("Rest of the code");
16. }
17. }
Output:UnhandledException:System.DivideBy
ZeroException: Attempted to divide by zero. Output: System.DivideByZeroException:
Attempted to divide by zero.
18 Prepared by Tesfa K. 5/15/2022
Rest of the code
Catching Exceptions – Example
Let’s now modify the code in our previous example to make it handle its exceptions.

static void ReadFile(string fileName) catch (FileNotFoundException fnfe)


{
{
// Exception handler for FileNotFoundException
// Exceptions could be thrown // We just inform the user that there is no such file
try Console.WriteLine("The file '{0}' is not found.", fileName);

{ }
TextReader reader = new StreamReader(fileName); catch (IOException ioe)
string line = reader.ReadLine(); {
//Exception handler for other input/output exceptions
Console.WriteLine(line);
// We just print the stack trace on the console
reader.Close(); Console.WriteLine(ioe.StackTrace);
} }
}

19 Prepared by Tesfa K. 5/15/2022


Catching Exceptions Description…
 When FileNotFoundException is thrown during the StreamReader
initialization, the CLR will not execute the lines following this statement, but will
jump to the row where we catch the exception catch (FileNotFoundException
fnfe):

catch (FileNotFoundException fnfe)


{
// Exception handler for FileNotFoundException
// We just inform the user that there is no such file
Console.WriteLine("The file '{0}' is not found.", fileName);
}
 In our example, users will simply be informed that such file does not
exist by a message printed on the standard output:
 The file 'WrongTextFile.txt' is not found.

20 Prepared by Tesfa K. 5/15/2022


Catching Exceptions Description…
 Similarly, if an IOException is thrown during reader.ReadLine(), it is
handled by the block below:
catch (IOException ioe)
{
//Exception handler for other input/output exceptions
// We just print the stack trace on the console
Console.WriteLine(ioe.StackTrace);
}
 In this case, we display the exception stack trace on the standard
output.
 The lines of code between where the exception is thrown and the
catch block are not executed.

21 Prepared by Tesfa K. 5/15/2022


Stack Trace:
 The stack trace contains detailed information about
the exception including where exactly it occurred in
the program.
 The stack trace is very useful for programmers when
they try to understand the problem causing the
exception.
 The information in the stack trace is very technical
and is designed to be used by programmers and
system administrators and not by the end users.

22 Prepared by Tesfa K. 5/15/2022


The throw keyword
 The throw statement allows you to create a custom error.
 The throw statement is used together with an exception class.
 There are many exception classes available in C#:
ArithmeticException, FileNotFoundException,
IndexOutOfRangeException,TimeOutException, etc:
Example
1. if (age < 18)
2. {
3. throw new ArithmeticException("Access denied - You must be at
least 18 years old.");
4. }
5. else
6. {
7. Console.WriteLine("Access granted - You are old enough!");
8. }
Output if age =15,
System.ArithmeticException: 'Access denied - You must be
at least 18 years old.'
23 Prepared by Tesfa K. 5/15/2022
try-finally Construct
 Every try block could contain a respective finally block.
 The code within the finally block is always executed, no
matter how the program flow leaves the try block.
 This guarantees that the finally block will be executed
even if an exception is thrown or a return statement is
executed within the try block.
 The finally block is a key tool for preventing resource
leaks.
 When closing a file or otherwise recovering resources,
place the code in a finally block to ensure that resource is
always recovered.

24 Prepared by Tesfa K. 5/15/2022


When Should We Use try-finally?
 Sometimes our program may deal with external programs
resources.
 Examples for external resources include files, network
connections, graphical elements and streams input
output from different hardware devices (like printers,
card readers and others).
 When we deal with such external resources, it is critically
important to free up the resources as early as possible when
the resource is no longer needed.
 For example, when we open a file to read its contents (let’s
say to load a .JPG image), we must close the file right after
we have read the contents.
 If we leave the file open, the operating system will prevent
other users and applications to make certain operations on the
file.

25 Prepared by Tesfa K. 5/15/2022


Resource Cleanup – Solving the Problem
 the fundamental step to process file is:-
open the file =>read =>close’.
 If an error occurs during opening or reading the file,
we will leave the file open.
 To solve this, we can use the try-finally construct.
 Here we have one resource to clean-up (in this case a
file).

26 Prepared by Tesfa K. 5/15/2022


 Closing a file stream could be done using the following pattern:
1. static void ReadFile(string fileName)
2. {
3. TextReader reader = null;
4. try
5. {
6. reader = new StreamReader(fileName);
7. string line = reader.ReadLine();
8. Console.WriteLine(line);
9. }
10. finally
11. {
12. // Always close "reader" (if it was opened)
13. if (reader != null)
14. {
15. reader.Close();
16. }
17. }
18. }

27 Prepared by Tesfa K. 5/15/2022


Example Description
 In the above example, we first declare the reader variable, and then initialize
the TextReader in a try block.
 Then in the finally block we close the reader.
 Whatever happens during TextReader’s initialization or during reading, it is
guaranteed that the file will be closed.
 If there is a problem initializing the reader (say the file is missing), then reader
will remain null and this is why we do a check for null in the finally block
before calling Close().
 If the value is indeed null, then the reader has not been initialized and there is
no need to close it.
 The code above guarantees that if the file has been opened, then it will be
closed no matter how the method exits.
 The example above should, in principle, properly handle all exceptions related
to opening and initialization of the reader (like FileNotFoundException).

28 Prepared by Tesfa K. 5/15/2022


1. class Program 19. catch(InvalidCastException env)
2. { 20. {
3. static void Main(string[] args) 21. Console.WriteLine("invalid type casting:);
4. { 22. }
5. usingThrwo(); 23. catch(DivideByZeroException dvd)
6. } 24. {
7. static void usingThrwo() 25. Console.WriteLine("div by zer not posbl:);
8. { 26. }
9. try 27. catch(IndexOutOfRangeException indx)
10. { 28. {
11. int val1, val2; 29. Console.WriteLine("index out of bound”);
12. Console.WriteLine("enter 2 number"); 30. }
13. val1=Convert.ToInt32(Console.ReadLine()); 31. }
14. val2=Convert.ToInt32(Console.ReadLine()); 32. static void div(int x,int y)
15. div(val1,val2); 33. {
16. int[] arr = new int[3] { 1, 2, 15 }; 34. Console.WriteLine(“Result"+(x/y));
17. arr[val1] = val2; 35. }
18. } 36. }

29 Prepared by Tesfa K. 5/15/2022


End of Chapter Four

30 Prepared by Tesfa K. 5/15/2022

You might also like