advertisement
Multiple Catch Block in C#
A try block can throw multiple types of executions, which must be handled by the catch block. c# allows defining multiple catch blocks to handle different types of executions that might be raised by the try block. Depending on the type of execution thrown by the try block, the appropriate catch block (if present) is executed. However, if the compiler does not find the appropriate catch block, then the general catch block is executed.
Once the catch block is executed, the program control is passed the finally block (if any) and then the control terminates the try-catch-finally construct.
EXAMPLE:
class program
{
static void Main(string[] args)
{
// codition 1
string[] names = { "john","james"};
// condition 2
int numone = 130;
int numtwo = 0;
int result = 0;
int index = 0;
try
{
index = 3;
names[index] = "kate";
result = numone / numtwo;
}
catch (DivideByZeroException divideobj)
{
Console.WriteLine("Divide By 0: "+divideobj);
}
catch(IndexOutOfRangeException indexobj)
{
Console.WriteLine("Wrong number of arguments: "+indexobj);
}
catch(Exception excobj)
{
Console.WriteLine("Error: "+excobj);
}
finally
{
Console.WriteLine(result);
Console.WriteLine();
for(int i = 0; i < 2; i++)
{
Console.WriteLine("Student Names: "+names[i]);
}
}
Console.ReadKey();
}
}
Define:-
Provided code, the array, and names are initialized to two element values, and two integer variables are declared and initialized. As there is a reference to a third array element, an exception of type IndexoutOfRangeException is thrown, and the second catch block is executed. Instead of hard. coding the index value, it could also happen that some mathematical operation results in the value of the index becoming more than 2. Since the try block encounters an exception in the first statement, the next statement in the try block is not executed and the control terminates the try-catch construct. So, the C# compiler prints the initialized value of the variable result and not the value obtained by dividing the two numbers. However, if an exception occurs that cannot be caught using either of the two catch blocks, then the last catch block with the general Exception class will be executed.
Exception Assistant
Exception assistant is a recently added feature for debugging C# applications. This assistant appears whenever a run-time exception occurs. It shows the type of exception that occurred, the troubleshooting tips, and the corrective action to be taken, and can also be used to view the details of an exception object. Exception assistant provides more information about an exception than the Exception dialog box. The assistant makes it easier to locate the cause of the exception and to solve the problem.
advertisement
Conversation
Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!
Join the discussion and share your insights now!
Comments 0