Updated on Kisan Patel
In C#, Exception is a run-time error that arises because of some abnormal conditions, such as a division of a number by zero, passing a string to a variable that holds an integer value.
Compile time errors are those errors that occur during compilation of a program. It can happen due to bad coding or incorrect syntax. You can correct these compile time errors after looking at the error message that the compiler generates.
Run time errors are those errors that occur during execution of a program and thus at that time they cannot be corrected. So you can handle those errors, when they occur by using try…catch statement.
C# provides the try…catch statement for exception handling. The try
block encloses those statements that can cause an error; whereas, the catch
block encloses the statements to handle the exception, it it occurs.
For Example,
using System; namespace ConsoleApp { class Program { static void Main(string[] args) { int number = 0; int p = 0; try { p = 100 / number; } catch (DivideByZeroException e) { Console.WriteLine("Exception Occured!"); } } } }
the above C# code will produce below output…
In above code, when 100 is divided by 0, the DivideByZeroException
occurs; and therefore, the program control is transferred to the catch
block and executes the statement inside the catch block.
You can also use finally with try…catch block as shown in below code. The statement enclosed inside finally block are always executed, irrespective of the fact whether an exception occurs or not.
try { p = 100 / number; } catch (DivideByZeroException e) { Console.WriteLine("Exception Occured!"); } finally { Console.WriteLine("The finally block executed!"); }
the above code will produce below output…
We can also print the Message and Stack Trace of the exception using Message
and the StackTrace
property of the Exception
class.
For Example,
try { p = 100 / number; } catch (Exception e) { Console.WriteLine("Message : "); Console.WriteLine(e.Message); Console.WriteLine("\nStack Trace : "); Console.WriteLine(e.StackTrace); }
the above C# code will produce below output…
Here, Message
properties of Exception class describes the exception and StackTrace
print out the filename along with its complete path and line number which contains the error for the exception.