Interview Questions and Answers on Exception handling in C# ( Part-1 )
Question: Will the code written after catch block be executed?
Answer : Yes, code written after Catch block will be executed. see the below example :
Here I am trying to generate 'DivideByZero' Exception that will be handled by catch block
and it will print exception message then program will also execute Console.WriteLine() statement and print "Code after exception block".
class Exception1
{
public static void Main()
{
CheckStatementAfterCatch();
Console.ReadLine();
}
public static void CheckStatementAfterCatch()
{
int a = 8;
int b = 0;
try
{
int c = a / b;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("Code after exception block");
}
}
Question 2: What will be output if program generates an exception and we only have finally block in code?
Answer : Here we have two scenario:
1. Method caller is calling your method inside try..catch block : In this scenario code will be executed, it will generate exception from try block (but not throw to caller) then finally block will be executed and after that exception would be passed to caller, caller will handle that exception.
2. Method caller is not using any try..catch block: In this scenario your program will crash....no meaning of finally bock in code.
No comments:
Post a Comment