0

I have below Child method which deal with DB calls. so this can produce normal exception or SQLexception also. so this code block have 2 catch blocks.

public void ChildMethod()
{
   try
   {
      //dbcall code
   }
   catch(Exception exc)
   {
      throw exc;
   }
   catch(sqlException sqlex)
   {
      throw sqlex;
   }
}

I have this Parent method which calls the Chile method. it have its own try catch block. But how to pass the base exception, e.g. suppose there is a exception from child class, i want to pass the same exception to the parent methods catch block, thus i can push the exception details to some other source.

Parent code

public void ParentMethod()
{
try{
chileMethod();
}
catch(exception ex)
{
ApplicaitonInsightlogging.Add(ex); // This ex should contain the Base exception.
}
Titi
  • 65
  • 7
  • Adding throw only should work? – Titi Dec 11 '18 at 10:47
  • 1
    @Titi yes, just write "throw;" inside catch blocks of the child method. – Akshay Raut Dec 11 '18 at 10:48
  • OK great, thanks alot. – Titi Dec 11 '18 at 10:49
  • Still i have a query, In my child class i will have different type of exception. exception, sqlexception. But in my parent class only exception type will be there. In case Sqlexception is thrown from child class will normal Exception in parent method will be able to handle it? – Titi Dec 11 '18 at 10:52
  • Please note exceptions are proceeded in the order you specify. So you need to change `Exception` and `SqlException` order. From MSDN: "Catch the more specific exceptions before the less specific ones. " (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch). – Miamy Dec 11 '18 at 10:54
  • 1
    Regarding you question - yes, the parent `Exception` block will be able to catch all exception types, because `Exception` is the parent for all of them. – Miamy Dec 11 '18 at 10:58
  • Chile? is that correct? – DanielV Aug 16 '22 at 16:25

1 Answers1

0

Simply rethrow the exception from child

public void ChildMethod()
{
   try
   {
      //dbcall code
   }
   catch(Exception exc)
   {
     throw;
     //Or throw exc; 
   ...

Notice that there is difference between “throw” and “throw ex”

tchelidze
  • 8,050
  • 1
  • 29
  • 49