Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If exception occurs in Catch block itself then how to handle it in C#?

Tags:

c#

asp.net

//I have written code in Catch Block

 try {

 } catch(Excepetion ex) {
        // I have written code here If Exception Occurs then how to handle it.
 }
like image 310
Atul Phadtare Avatar asked Nov 28 '12 04:11

Atul Phadtare


People also ask

What happens when there is a exception in the catch block itself?

Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.

How do you handle exceptions inside a catch block?

Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.

Can we handle exception in catch block?

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception. Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final .

What happens if an exception is thrown outside a catch block?

If a catch block ends normally, without a throw , the flow of control passes over all other catch blocks associated with the try block. Whenever an exception is thrown and caught, and control is returned outside of the function that threw the exception, stack unwinding takes place.


1 Answers

The best way is to develop your own exceptions for different Layers of application and throw it with inner exception. It will be handled at the next layer of your application. If you think, that you can get a new Exception in the catch block, just re throw this exception without handling.

Let's imagine that you have two layers: Business Logic Layer (BLL) and Data Access Layer (DAL) and in a catch block of DAL you have an exception.

DAL:

try
{
}
catch(Excepetion ex)
{
  // if you don't know how should you handle this exception 
  // you should throw your own exception and include ex like inner exception.
   throw new MyDALException(ex);
}

BLL:

try
{
  // trying to use DAL
}
catch(MyDALException ex)
{
  // handling
}
catch(Exception ex)
{
   throw new MyBLLException(ex);
}
like image 59
Warlock Avatar answered Sep 28 '22 08:09

Warlock