Can we throw a custom exception from catch block?

1.2k views Asked by At

I want to throw a custom exception from catch block, i.e., whenever any exception occurs it should catch by catch block and will throw a custom exception. I am trying with the below code but getting runtime exception in catch block as "unhandled exception".

try{
  ///some error
 }
      catch(Exception e){
    try{
          throw new CustomException("Exception1", e);
        }
    catch(CustomException ce)
       {
        Console.WriteLine("Custom Exception Caught" + ce.StackTrace);

       }
 }


public class CustomException : Exception
 {

   public CustomException : base()
    {
    }

  public CustomException(string message, Exception innerException) : base(message, innerException)
   {
     processError(message, innerException);
   }
 }

 public static void processError(string mgs, Exception e)
  {
   switch(mgs)
    {
     case "Exception1":
        Console.WriteLine("Exception1 caught" + e.StackTrace);
        break;
     case "Exception2":
        Console.WriteLine("Exception2 caught" + e.StackTrace);
        break;
     default:
        Console.WriteLine("Some other Exception caught" + e.StackTrace);
        break;
       }
    }

Any hint on the above problem is highly appreciated. Thanks in advance.

1

There are 1 answers

0
D. Scott Boggs On BEST ANSWER

Yes, simply write

throws new ExceptionType(parameter);

where ExceptionType is the name of the custom exception class.