An exception is a problem that arises during the execution of a program. We have four keywords: try, catch, finally and throw to handle them.
Problem 1: Write normal try/catch blocks.
Solution
- try
- {
-
- }
- catch (Exception ex1)
- {
-
- }
- finally
- {
-
-
- }
Problem 2: If I am throwing a DivideByZeroException from a try block and I have 2 catch blocks then the first one with the Exception class and the second with the DivideByZeroException exception class, which will execute?
Solution
It will give an error as in the following:
Image 1.You can write your code as in the following:
- try
- {
- throw new DivideByZeroException();
- }
- catch (DivideByZeroException ex1)
- {
- Console.WriteLine("In DivideByZeroException Catch Block");
- }
- catch (Exception ex)
- {
- Console.WriteLine("In Exception Catch Block");
- }
- finally
- {
- Console.WriteLine("Finally Block");
- }
Output will be: Image 2.Problem 3: Can we have a try without a catch?
Solution: Yes but in this case I need to use a finally block as in the following:
First if I don't use a finally block then it will give an error:
Image 3.If I use finally then I can use a try without a catch like in the following code:
- try
- {
-
- Console.WriteLine("In Try Block");
- }
- finally
- {
-
-
- Console.WriteLine("In Finally Block");
- }
Output:
Image 4.Problem 4: If I write the following code then will the following exception occur:
- try
- {
- Console.WriteLine("In Try Block");
- throw new DivideByZeroException();
- }
- catch (DivideByZeroException ex1)
- {
- Console.WriteLine("In DivideByZeroException Catch Block");
- throw new DivideByZeroException();
- }
- catch (Exception ex)
- {
- Console.WriteLine("In Exception Catch Block");
- throw new DivideByZeroException();
- }
- finally
- {
- Console.WriteLine("Finally Block");
- }
Solution: Yes like in the following image.
Image 5.Problem 5: What is the difference between Throw Exception and the Throw Clause.
Solution: See both in the following code:
Image 6.The difference is the Stack Trace Information that gets sent with the exception."When you throw an
exception using "
throw ex" then you override the original stack trace with a new stack trace that starts from the throwing method."
Throw
In Throw, the original exception stack trace will be retained. To keep the original stack trace information, the correct syntax is "throw" without specifying an exception.
Throw ex
In Throw ex, the original stack trace information will be overriden and you will lose the original exception stack trace. In other words "throw ex" resets the stack trace.