C# Exception Handling PDF

Document Details

PhenomenalAmber4016

Uploaded by PhenomenalAmber4016

Sangola Mahavidyalaya Sangola

Tags

C# exception handling exception handling programming C#

Summary

This document provides an overview of exception handling in C#. It details the concept, syntax, and examples of how exceptions can be handled in a program. It also describes several exception types and their common causes.

Full Transcript

Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO UNIT-III Exception, Threading and Resource Management C# Exception Definition -An exception is a runtime error which results in abnormal termination of program. A C# exception is a respons...

Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO UNIT-III Exception, Threading and Resource Management C# Exception Definition -An exception is a runtime error which results in abnormal termination of program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exception handling is used to make sure that the program flow is continued even if there is a runtime error. Exceptions are the objects that are thrown while encountering any runtime error. If the exceptions are not handled, then C# will produce an exception message and will terminate the program abnormally, this is where exception handling comes into the picture. The following example shows program execution with an exception. As you can see, in the below code, we are dividing an integer number by 0 which is not possible in mathematics. So, it will throw the DivideByZeroException in this case. The statements which are present before the exception-causing statement i.e. before c = a / b; is executed and the statements which are present after the exception-causing statement will not be executed. using System; namespace ExceptionHandlingDemo { class Program { static void Main(string[] args) { int a = 20; int b = 0; int c; Console.WriteLine("A VALUE = " + a); Console.WriteLine("B VALUE = " + b); c = a / b; Console.WriteLine("C VALUE = " + c); Console.ReadKey(); } } } 1|Page SANGOLA MAHAVIDYALAYA SANGOLA Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO Output: After printing the above value it will give us the below error Keywords for Exception Handling Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally, and throw.  try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.  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.  finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.  throw − A program throws an exception when a problem shows up. This is done using a throw keyword. 2|Page SANGOLA MAHAVIDYALAYA SANGOLA Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO Syntax- try { // put the code here that may raise exceptions } catch { // handle exception here } finally { // final cleanup code } Exception Handling in C# using Try-Catch Implementation namespace ExceptionDemo { class Program { static void Main(string[] args) { Console.WriteLine("Enter Values For a and b...."); int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); try { int c = a / b; Console.WriteLine("Result=" + c); } catch(Exception e) { Console.WriteLine(e.Message); } Console.WriteLine("EOF PROGRAM........"); Console.ReadKey(); } } } Output- Enter Values For a and b.... 10 3|Page SANGOLA MAHAVIDYALAYA SANGOLA Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO 0 Attempted to divide by zero. EOF PROGRAM........ Exceptions Class Hierarchy All the exceptions in the C# are derived directly or indirectly from the System.Exception class. Fig.Exception hierarchy in C# The above image shows the exception hierarchy in C#. C# provides a base class named Exception which is later derived into other classes. The major two exception classes derived from the Exception class are: 1. SystemException - also called built-in exceptions 2. ApplicationException - also called user-defined exceptions 4|Page SANGOLA MAHAVIDYALAYA SANGOLA Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO Following Table shows List of common System Exceptions, Example: C# SystemException using System; class Program { string[] colors = { "Red", "Green", "Pink" }; static void Main() { // print the array element present at 3rd index position 5|Page SANGOLA MAHAVIDYALAYA SANGOLA Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO Console.WriteLine(colors); } } Output Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array. In the above example, we are trying to access the index 3 element of the colors array element. Since there is no element at index 3, the program throws a system exception IndexOutOfRangeException. 2)Application Exception / User-defined Exception We can also create user-defined exceptions which are known as Application level exceptions. The ApplicationException class is the base class from which we can derive application-level exceptions. An exception that is raised explicitly under a program based on our own condition (i.e. user-defined condition) is known as an application exception or Custom Exception. As a programmer, we can raise application exceptions at any given point in time. To raise an Application Exception in C#, we need to adopt the following process. First, we need to create a custom Exception class by inheriting it from the Parent Exception class and then we need to create an instance of the Custom Exception class and then we need to throw that instance. namespace CustomExceptionDemo { class MyException:ApplicationException { public void showerror() { Console.WriteLine("EXCEPTION RAISED....ODD NUMBER IS NOT ALLOWED...."); } 6|Page SANGOLA MAHAVIDYALAYA SANGOLA Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO } class Program { static void Main(string[] args) { Console.WriteLine("Enter only even number...."); int n = Convert.ToInt32(Console.ReadLine()); try { if (n % 2 != 0) throw new MyException(); else Console.WriteLine("Square of Even number..." + n + "IS " + (n * n)); } catch(MyException e) { e.showerror(); } Console.ReadKey(); } } } Output- Enter only even number.... 7 EXCEPTION RAISED....ODD NUMBER IS NOT ALLOWED.... Multiple Catch Blocks- In C#, you can use more than one catch block with the try block. Generally, multiple catch blocks is used to handle different types of exceptions means each catch block is used to handle different type of exception. If you use multiple catch blocks for the same type of exception, then it will give you a compile-time error because C# does not allow you to use multiple catch 7|Page SANGOLA MAHAVIDYALAYA SANGOLA Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO block for the same type of exception. A catch block is always preceded by the try block. In general, the catch block is checked within the order in which they have occurred in the program. If the given type of exception is matched with the first catch block, then first catch block executes and the remaining of the catch blocks are ignored. And if the starting catch block is not suitable for the exception type, then compiler search for the next catch block. Syntax: try { // Your code } // 1st catch block catch(Exception_Name) { // Code } // 2nd catch block catch(Exception_Name) { // Code } Ex) using System; namespace ExceptionHandlingDemo { class Program { static void Main(string[] args) 8|Page SANGOLA MAHAVIDYALAYA SANGOLA Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO { int Number1, Number2, Result; try { Console.WriteLine("Enter First Number"); Number1 = int.Parse(Console.ReadLine()); Console.WriteLine("Enter Second Number"); Number2 = int.Parse(Console.ReadLine()); Result = Number1 / Number2; Console.WriteLine("Result: "+Result); } catch (DivideByZeroException DBZE) { Console.WriteLine("Second Number Should Not Be Zero"); } catch (FormatException FE) { Console.WriteLine("Enter Only Integer Numbers"); } catch (Exception ex) { Console.WriteLine("Generic Catch Block..."); } Console.ReadKey(); } } } Output-1) 9|Page SANGOLA MAHAVIDYALAYA SANGOLA Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO Output-2) Output-3) The try-finally Construct- try block must be followed by either catch or finally block  The finally block does not contain any return, continue, break statements because it does not allow controls to leave the finally block.  You can also use finally block only with a try block means without a catch block but in this situation, no exceptions are handled.  The finally block will be executed after the try and catch blocks, but before control transfers back to its origin. namespace tryfinallyDemo; class Program { public static void check(int a,int b) { try { if(b==0) { throw new DivideByZeroException(); } else { Console.WriteLine("Division a/b="+(a/b)); } 10 | P a g e SANGOLA MAHAVIDYALAYA SANGOLA Unit 3: Threading, Exception and Resource Mgt. 24- 25 SHIVRATNA HONRAO } finally { Console.WriteLine("Written inside Finally Block....."); } } static void Main(string[] args) { Console.WriteLine("Enter Value for a..."); int a=Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter Value for b..."); int b=Convert.ToInt32(Console.ReadLine()); try { check(a,b); } catch(DivideByZeroException de) { Console.WriteLine("EXCEPTION RAISED...."+de.Message); } } } 11 | P a g e SANGOLA MAHAVIDYALAYA SANGOLA

Use Quizgecko on...
Browser
Browser