0% found this document useful (0 votes)
3 views

Module 4 C# Latest

The document provides an overview of exception handling in C#, explaining what exceptions are and how to manage them using try, catch, and finally blocks. It discusses various types of exceptions, including DivideByZero and Format exceptions, and demonstrates how to implement multiple catch statements and user-defined exceptions. Additionally, it covers the concepts of checked and unchecked contexts for handling arithmetic overflow in C#.

Uploaded by

Shashank S
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)
3 views

Module 4 C# Latest

The document provides an overview of exception handling in C#, explaining what exceptions are and how to manage them using try, catch, and finally blocks. It discusses various types of exceptions, including DivideByZero and Format exceptions, and demonstrates how to implement multiple catch statements and user-defined exceptions. Additionally, it covers the concepts of checked and unchecked contexts for handling arithmetic overflow in C#.

Uploaded by

Shashank S
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/ 27

Module 4

Exceptional Handling
What are exceptions in C#?
An exception is defined as an event that occurs during the execution of a program that
is unexpected by the program code. The actions to be performed in case of occurrence
of an exception is not known to the program. In such a case, we create an exception
object and call the exception handler code.
Keyword Definition
Used to define a try block. This block holds the code that may
try
throw an exception.
Used to define a catch block. This block catches the exception
catch
thrown by the try block.
finally Used to define the finally block. This block holds the default code.
throw Used to throw an exception manually.
Write a program to divide two numbers

• Using system;
• Public class Example
• {
• Public static void main()
• { Console.WriteLine(“Enter two numbers”);
• Int a = int.Parse(Console.ReadLine());
• Int b = int.Parse(Console.ReadLine());
• Int c = a/b;
• Console.WriteLine(“The division of two numbers is :” +c);
• Console.WriteLine(“End of the Program”);
• }
• }What is the output a=4,b =2;
• The division of two numbers is 2
• End of the program
• What is the output a=4,b=0;
• System.32 Divide by zero Exception.
• For the above input the program is terminated abruptly.
• What happens when exception occurs in the program?
• The later lines will not execute
• Abnormal termination
• How to handle this problem?
• Using Exception Handling
• What is Exception Handling?
• Exception handling is the process of responding to unwanted or
unexpected events when a computer program runs. We can display user
friendly error messages so that we can describe the error.
• We can perform the corrective actions to resolve the problem that may
come in to the picture due to the error.
• To handle these errors we will put this code under try catch block
Syntax:
Try
{ //statements when run time error occur
Statements which doesn’t require execution when the error got occur.
}
Catch
{
// only the code when a exception causing lines for the corrective action
}
• Using system;
• Public class Example
• {
• Public static void main()
• { Console.WriteLine(“Enter two numbers”);
• Int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine());
• try
• {
• Int c = a/b;
• Console.WriteLine(“The division of two numbers is :” +c);
• }
• Catch(DivideByZero Ex)
• {
• Console.WriteLine(Ex.Message);
• }

• Console.WriteLine(“End of the Program”);


• }
• What will be the out put of the above program.
• For the same program if a=4, b =‘x’, we encounter another exception. We
will get exception as format exception.
• Hence for the above program we have two exceptions:
• i) Divide by zero
• Ii) Format exception.
• Hence we need two catches for two exceptions, These leads to multiple
catch statements.
• Rewrite the division program using multiple catch statements.
• Syntax:
• Try
• {//code}
• Catch(exception1 )
• {//code}
• catch(exception 2)
• {//code}
• For the same division program if a=444444444444, b=2,
• What will be the exception?
• Overflow exception.
• As we cannot write catch statement for every exception, we can use a General
catch Handler
• It works as default statement in Swich –case
• Rewrite the above division program using general catch handler.
Exception OverView:
Exceptions have the following properties:
•Exceptions are types that all ultimately derive from System.Exception.

•Use a try block around the statements that might throw exceptions.
•Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler
• that is present anywhere in the call stack. In C#, the catch keyword is used to define an exception handler.
•If no exception handler for a given exception is present, the program stops executing with an error message.
•Don't catch an exception unless you can handle it and leave the application in a known state.
•If you catch System.Exception, rethrow it using the throw keyword at the end of the catch block.
•If a catch block defines an exception variable, you can use it to obtain more information
about the type of exception that occurred.
•Exceptions can be explicitly generated by a program by using the throw keyword.
•Exception objects contain detailed information about the error,
•such as the state of the call stack and a text description of the error.
•Code in a finally block is executed regardless of if an exception is thrown. Use a finally block to release resources
•, for example to close any streams or files that were opened in the try block.
•Managed exceptions in .NET are implemented on top of the Win32 structured exception handling mechanism
Divide by zero exception Program
• using System;

• public class Example


• {
• public static void Main()
• {
• int number1 = 3000;
• int number2 = 0;
• try {
• Console.WriteLine(number1 / number2);
• }
• catch (DivideByZeroException e ) {
• Console.WriteLine(e.message);
• }

• }
• }
• Catch(format execption)
•{
• Console.writeline(“The input should be numeric value”);
•}
• Catch(Exception ex) // works as default in switch case
•{
• Console.writeline(ex.message);
•}
• Console.writeline(“End of the program”);
•}
•}
• If all the statements execute with out any exception the control will jump to the
first statement after the catch blocks.
• If there is any exception the corresponding catch will execute and retains from
abnormal termination and the control will jump to the first statement after the
catch.
• Try
• { // code which run when there are no exceptions
•}
• Catch(Exception ex)
• { // code which runs when there are exceptions
•}
• Finally
• { // code which run if exceptions are there or not
•}
• Using system;
• Class ExceptionDemo
•{
• Public static void main()
•{
• Try
•{
• Int a =int.parse(console.ReadLine());
• Int b = int.parse(console.ReadLine());
• C=a/b;
• Console.writeLine(“The result : +C);
• return;
•}
• catch (DivideByZeroException e ) {
• Console.WriteLine(e.message);
• }
• Catch(format execption)
• {
• Console.writeline(“The input should be numeric value”);
• }
• Catch(Exception ex) // works as default in switch case
• {
• Console.writeline(ex.message);
• }
• Finally
• {
• Console.writeline(“This program has to be executed at any cost”);
• }
• Console.writeline(“End of the program”);
• }
• }
• Add the following code for the above program and test in the lab
• If(b==1)
• return;

• In any conventional program return statement makes the control to jump


at the end of the program.
• But when a finally block is given the return statement will jump to finally
and end the program.
• Even if catch block is not there, Abnormal termination occurs but ‘Finally’
block executes(Try in the Lab)
Nested try Blocks
• In C#, the nesting of the try & catch block is allowed. The nesting of try
block means one try block can be nested into another try block. The
various programmer uses the outer try block to handling serious
exceptions, whereas the inner block for handling normal exceptions.
• Note:
• If an exception raises in the inner try block that is not caught by the
catch block associated with the try block, then the exception is promoted
to the outer try block. Generally, nested try blocks are used to permit
different groups of the error to be handled in different ways.
• It is a necessary condition that a try block must be followed by a catch or
finally blocks because if you use a try block without a catch or finally
then you will tend to a compile-time error.
Syntax
• try

• {

• try

• {

• }

• Catch(Exception1)// Inner catch

• {

• }

• }

• Catch(Exception)// outer catch

• {

• }
• class nestedtrydemo
• {

• // Main Method
• public static void Main(string[] args)
• { try
• {
• Console.WriteLine("Enter two numbers to divide");

• int a= int. Parse(Console.ReadLine());


• int b = int.Parse(Console.ReadLine());
• try
• {
• int c = a / b;
• Console.WriteLine("The result is :" + c);
• ; }

• // Catch block for inner try block


• catch (DivideByZeroException)
• {

• Console.WriteLine("Inner Try Catch Block");


• }

• // Catch block for outer try block
• catch (FormatException)
• {

• Console.WriteLine("Outer Try Catch Block");

• }
• }
• }

Write a c# code to read array of elements and a divisor, divide each element of the array with the divisor
i) Check the exception IndexOutOf Range for the array range of elements in the outer try block
ii) Check DividebyZero exception in inner try block.
The Exception Hierarchy
System Exception Vs Application Exception
• System Exception Application Exception
1)These Exception are System 1) These are user defined
Defined
2)Predefined classes are there in 2) Application Developer creates
the system library class and gets inherited from
Base class(Which is predefined)
3)All Exceptions are raised by CLR 3)CLR will not throw any exception
4)Some System Exceptions are: 4)Developer can create his own
exceptions like DivideByOddNumber.
i) DivideByZero
ii)IndexOutOfRange
iii)Format
Application Exception(User Defined Exceptions)

• Developer has to create his own exception, CLR will not throw as it is not a
universal Exception.
• Developer creates a class under the class Exception.
• ApplicationException Ex = New ApplicationExeption(“<Error Message>”)
• Throw ex;
• Or
• Throw new AppliacationException(“<ErrorMessage>”)
Program demonstrating user defined exception

• using System;
• class UserException
• {
• public static void Main(string[] args)
• {
• int age;
• Console.WriteLine("Enter the age of a person");

• try
• {
• age = int.Parse(Console.ReadLine());
• if (age < 18)
• throw new Exception();

• }
• catch (Exception ex)
• {
• Console.WriteLine("Age not eligible for
voting");
• }
• Console.WriteLine("End of the program");
• }
•}
• Write a c# code Throw InsufficientFundsException if
the user enters the amount greater than the balance
in case of withdrawing operations.
• Checked and Unchecked:
• C# provides checked and unchecked keyword to handle integral type
exceptions. Checked and unchecked keywords specify checked
context and unchecked context respectively. In checked context,
arithmetic overflow raises an exception whereas, in an unchecked
context, arithmetic overflow is ignored and result is truncated.
• C# Checked
• The checked keyword is used to explicitly check overflow and
conversion of integral type values at compile time.
• Let's first see an example that does not use checked keyword.
• C# Checked Example without using checked
1.using System;
2.namespace CSharpProgram
3.{
4. class Program
5. {
6. static void Main(string[] args)
7. {
8. unchecked
9. {
10. int val = int.MaxValue;
11. Console.WriteLine(val + 2);
12. }
13. }
14. }
15.}
C# Checked Example using checked
• This program throws an exception and stops program execution.
1.using System;
2.namespace CSharpProgram
3.{
4. class Program
5. {
6. static void Main(string[] args)
7. {
8. checked
9. {
10. int val = int.MaxValue;
11. Console.WriteLine(val + 2);
12. }
13. }
14. }
15.}

You might also like