Exception Handling
Exception Handling
Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution. C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.
Exception Handling
The general form try-catch-finally in C# is shown below try { // Statement which can cause an exception. } catch(Type x) { // Statements for handling the exception } finally { //Any cleanup code }
Both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.
Exceptions
In C#, exceptions are nothing but objects of the type Exception class. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc.
using System; class MyClient { public static void Main() { int x = 0; int div = 100/x; Console.WriteLine(div); } }
Output
//C#: Exception Handling using System; class MyClient { public static void Main() { int x = 0; int div = 0; try { div = 100 / x; Console.WriteLine("This line is not executed"); } catch (DivideByZeroException de) { Console.WriteLine("Exception occured"); } Console.WriteLine("Result is {0}", div); } }
Output
Finally Block
The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits. Whereas catch is used to handle exceptions that occur in a statement block, finally is used to guarantee an executable block of code regardless of how the preceding try block is exited.
Output
using System; class MyClient { public static void Main() { int x = 0; int div = 0; try { div = 100/x; Console.WriteLine("Not executed line"); }
catch(DivideByZeroException de) { Console.WriteLine("DivideByZeroExceptio n" ); } catch(Exception ee) { Console.WriteLine("Exception" ); } finally { Console.WriteLine("Finally Block"); } Console.WriteLine("Result is {0}",div); } }
Output
In the previous program two catch blocks were defined one a general form and another a specialised one. more specialized catch block should come before a generalized one. A try block can throw multiple exceptions, which can be handled by using multiple catch blocks.
By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block. since in C#, all exceptions are directly or indirectly inherited from the Exception class.
Program example
using System; class MyClient { public static void Main() { int[] x = new int[5]; try { for (int i = 0; i <= 4; i++) { Console.WriteLine("Enter number:"); x[i] = int.Parse(Console.ReadLine()); }
for (int j = 0; j <= 5; j++) Console.Write("{o},", x[j]); }//try catch { Console.WriteLine(" Array out of bound Exception" ); }//catch }//main }
Output
Throwing an Exception
The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution. In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this purpose. The general form of throwing an exception is as follows. For example the following statement throw an ArgumentException explicitly. throw new ArgumentException("Exception");
Program Example
using System; catch (DivideByZeroException e) class MyClient { { Console.WriteLine("Exception"); public static void Main() } { Console.WriteLine("LAST int x = 10, y = 0; STATEMENT"); try } { Console.WriteLine("{0}", x } / y); if (y==0) { throw new DivideByZeroException ("Invalid Division"); } }
Output
using System; class MyClient { public static void Main() { int[] x = new int[5]; try { try { for (int i = 0; i <= 4; i++) { Console.WriteLine("Enter number:"); x[i]=int.Parse(Console.ReadLine()); } }//inner try catch (Exception e) { Console.WriteLine("string not in correct format"); }
Standard Exceptions
System.OutOfMemoryException System.NullReferenceException System.InvalidCastException System.ArrayTypeMismatchException System.IndexOutOfRangeException System.ArithmeticException System.DevideByZeroException System.OverFlowException
In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes.
Program example
using System; class MyException : Exception { public MyException() { Console.WriteLine("User defined exception"); } } class MyClient { public static void Main() { try { throw new MyException(); } catch(Exception e) { Console.WriteLine("Exception caught here :" + e.ToString()); } Console.WriteLine("LAST STATEMENT"); } }
Checked Operator
The checked keyword is used to explicitly enable overflow-checking for integral-type arithmetic operations and conversions. By default, if an expression produces a value that is outside the range of the destination type, constant expressions cause compile-time errors, and non-constant expressions are evaluated at run-time and raise exceptions. However, the checked keyword can be used to enable checking .of overflow and display the message instead of showing an erroneous result.
Programming example
using System; class abc { public static void Main() { short x=32767; short y=32767; short z; try { z =checked(x + y); Console.WriteLine(z); } catch (OverflowException exc) { Console.WriteLine(exc); } } }
Unchecked Operator
The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions. In an unchecked context, if an expression produces a value that is outside the range of the destination type, the result is truncated.
Programming Example
using System; class s1 { public static void Main() { int x = unchecked(2147367847 * 2); System.Console.WriteLine("i={0}", x); }
} Output: i=-231602
C# does not need header files Class definition does not use semicolon(;) at end. The first character of main is capital. C# does not support #include All data types in C# are inherited from object superclass and are objects. All the basic value types will have the same size on any system.
C# checks for uninitialised variables and give error messages at compile time.While in C++ and uninitialised variable goes undetected and can give garbage values. C# supports string types.Strings are implemented as character arrays. C# does not support pointers while C++ does. We can only create objects in C# using new operator.
C# supports foreach statement while C++ doesnt. C# doesnt allow a fallthrough in switch statement. C# doesnt provide copy constructors. C# doesnt support macros. C# doesnt support multiple inheritence,typedef statement. C# doesnt support Forward class declaration. C# doesnt support Friend function. C# has automatic garbage collection. C# has Delegates and events. C# has boxing and unboxing
Unlike java all C# data types are objects. Arrays are declared differently in C#. Java uses static final to declare a class constant while C# uses const. The convention of java is to put one public class in each file. C# support struct while java does not. Java does not support operator overloading. Java does not support enumeration. Switch statement in java can have only integer expressions but in c# both string and int is allowed. C# allows a variable no of arguments in params keyword. Java does not support indexers.