Ch-3 Edited Exception
Ch-3 Edited Exception
1
Exception, C#
When we write a program, we describe step-by-step what the computer must do and
in most of the cases we rely that the program will execute normally.
Indeed, most of the time, programs are following this normal pattern, but there are
some exceptions.
Let’s say we want to read a file and display its contents on the screen.
Let’s assume 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.
2
Exception in Object-Oriented Programming, 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.
3
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).
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.
4
Throwing an Exception, here is an example for a code that will throw an exception
using namespace std;
int main()
{
int x = -1;
// Some code
cout << "Before try \n";
try {
cout << "Inside try \n";
if (x < 0)
{
throw x;
cout << "After throw (Never executed) \n";
} Before try
} Inside try
catch (int x ) {
cout << "Exception Caught \n"; Exception Caught
} After catch (Will be executed)
cout << "After catch (Will be executed) \n";
return 0;
Catching Exceptions in C#...
The described method call and exception handling process could be visualized in the following
diagram (steps 1 through 5):
6
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.
• It is an event or object which is thrown at runtime. All exceptions are derived
from System.Exception class. It is a runtime error which can be handled. If
we don't handle the exception, it prints exception message and terminates the
program.
Advantage:
• It maintains the normal flow of the application. In such case, rest of the code is
executed event after exception.
• Allows you to separate error-handling code from the normal code. As a result, the
code is less complex, more readable and, at times, more efficient.
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.
Continued …..
Exception Class Cause of Exception
11
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 or 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.
12
Before exception is handled and after the exception is handled
1.using System;
1. using System; 2.public class ExExample
3.{
2. public class Example 4. public static void Main(string[] args)
3. { 5. {
6. try
4. public static void Main(string[] args)
7. {
5. { 8. int a = 10;
6. int a = 10; 9. int b = 0;
10. int x = a / b;
7. int b = 0; 11. }
8. int x = a/b; 12. catch (Exception e)
13. {
9. Console.WriteLine("Rest of the code"); 14. Console.WriteLine(e); }
10. } 15. Console.WriteLine("Rest of the code");
16. }
11. } 17.}
Output: System.DivideByZeroException: Attempted to
Output:UnhandledException:System.DivideByZeroException: divide by zero.
Attempted to divide by zero. Rest of the code
Catching Exceptions – Example
Let’s now modify the code in our previous example to make it handle its exceptions.
To do this, we wrap the code that could create problems in try-catch and then we add catch
blocks to handle the two types of exceptions we know could arise.
15
Similarly, if an IOException is thrown during reader.ReadLine(), it is handled by the block
below:
catch (IOException ioe)
{
// Exception handler for FileNotFoundException
// We just print the stack trace on the screen
Console.WriteLine(ioe.StackTrace);
}
In this case, we display the exception stack trace on the standard output.
The lines between where the exception is thrown and the catch block that processed
it are not executed.
16
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.
During debugging the stack trace is a priceless tool.
17
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.'
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.
19
When Should We Use try-finally?
In many applications we have to work with external for our programs resources.
Examples for external resources include files, network connections, graphical
elements, pipes and streams to or 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.
20
Resource Cleanup – Solving the Problem
In the previous section, we explained the fundamental flow of the solution '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.
We will first discuss the case in which we have one resource to clean-up (in this
case a file).
Then we will give an example when we have two or more resources.
21
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. } 22
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).
23
Multiple Catch Blocks
• A try block can be followed by multiple catch blocks. The syntax for
multiple catch blocks looks like the following
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block }
The Finally Block
• The finally block follows a try block or a catch block. A finally block of code
always executes, irrespective of occurrence of an Exception.
• Using a finally block allows you to run any cleanup-type statements that you want
to execute, no matter what happens in the protected code.
• A finally block appears at the end of the catch blocks and has the following syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes. }
Practical Exercises from the Chapter
1. 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.
2. Write a method that takes as a parameter the name of a binary file, reads the
content of the file and returns it as an array of bytes. Write a method that writes the
file content to another file. Compare both files.
3. Write a method that takes as a parameter the name of a text file, reads the file and
returns its content as string. What should the method do if and exception is
thrown?
26
19. catch(InvalidCastException env)
20. {
21. Console.WriteLine("invalid type casting:);
22. }
23. catch(DivideByZeroException dvd)
1. class Program 24. {
2. { 25. Console.WriteLine("div by zer not posbl:);
3. static void Main(string[] args) 26. }
27. catch(IndexOutOfRangeException indx)
4. { 28. {
5. usingThrwo(); 29. Console.WriteLine("index out of bound”);
6. } 30. }
7. static void usingThrwo() 31. }
8. { 32. static void div(int x,int y)
9. try 33. {
10. { 34. Console.WriteLine(“Result"+(x+y));
35. }
11. int val1, val2; 36. }
12. Console.WriteLine("enter 2 number");
13. val1 Convert.ToInt32(Console.ReadLine());
14. val2 Convert.ToInt32(Console.ReadLine());
15. div(val1,val2);
16. int[] arr = new int[3] { 1, 2, 15 };
17. arr[val1] = val2;
18. }
Individual assignment
1. What is exception and why it is necessary to handle it?
2. If result =x/y; and let y=0;what types of exception will be
generated when it is compiled;
3. Handle the following exception using try catch construct.
Hint: handle it in try with multiple catchs
1. int x = 10; y = 0;
2. int result = x / y;
3. int[] arr = { 1, 2, 15 };
4. arr[10] = 100;
4. What is Stack Trace in exception ?
Continued …
5. What is the difference between try-catch vs try finally
constructs.
6. The type of exception that handles the Input Output errors is
called?__.
7. Handle the following exception using throw construct.
5. int x = 10,y = 0;
6. int[] arr = { 1, 2, 15 };
7. Console.Write(x/y);
8. Console.Write(arr[25]);