Module 4 C# Latest
Module 4 C# Latest
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);
• }
•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;
• }
• }
• 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;
• {
• try
• {
• }
• {
• }
• }
• {
• }
• class nestedtrydemo
• {
• // Main Method
• public static void Main(string[] args)
• { try
• {
• Console.WriteLine("Enter two numbers to divide");
• }
• }
• }
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.}