In this article we are going to discuss Exception Handling Question in C#. There are many blogs, articles are available on the internet regarding Exception Handling Question but in this particular article I will try to explain to you with as much as simplest and realistic examples so you can get a clear idea of the Exception Handling Question use in C#.
1. Can we execute multiple Catch blocks?
NO, We can write multiple catch blocks but when we will run the application and if any error occur, only one out of them will execute based on the type of error.
try
{
int a = 10;
int b = 0;
int x = a / b;
}
// Catch block for invalid array access
catch (IndexOutOfRangeException e)
{
Console.WriteLine("An Exception has occurred : {0}", e.Message);
}
// Catch block for attempt to divide by zero
catch (DivideByZeroException e)
{
Console.WriteLine("An Exception has occurred : {0}", e.Message);
}
// Catch block for value being out of range
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine("An Exception has occurred : {0}", e.Message);
}
catch (Exception e)
{
Console.WriteLine(e);
}
2. Can we have only “Try” block without “Catch” block in real applications?
YES - We can have only try block without catch block, but then we must have finally block with try block.
try
{
int a = 10;
int b = 0;
int x = a / b;
}
finally
{
Console.WriteLine("The 'try catch' is finished.Finally block is executed");
}
Console.ReadKey();
3. Can we define catch(Exception e) before other catch block?
No, in C#, you cannot define catch (Exception ex) before other more specific catch blocks. The catch blocks are evaluated in order, and once a catch block that matches the exception is found, it is executed. If you place a general catch (Exception ex) block before more specific catch blocks, the specific ones will never be reached, as all exceptions are derived from Exception. It will show an error: