0

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.

Anand
  • 823
  • 1
  • 10
  • 19
  • "but getting error" is far too vague for us to help you. When are you getting the error - at compile time or execution time? If it's at execution time, that's presumably because nothing's catching the `CustomException` you're throwing... – Jon Skeet Nov 17 '14 at 06:37
  • @ Jin Skeet, Edited as per your doubt. – Anand Nov 17 '14 at 06:52
  • Your edit shows you catching the `CustomException` if that's thrown within the `try` block - but you're throwing it from the `catch` block below... that new exception isn't going to be caught by the catch block above it. It's unclear what you want to happen here - do you want it to throw the `CustomException` or not? – Jon Skeet Nov 17 '14 at 06:53
  • When ever any exception occurs I want to throw custom exception @ Jin Skeet – Anand Nov 17 '14 at 07:15
  • Well it sounds like that's already happening. The custom exception is being thrown... what's the problem? – Jon Skeet Nov 17 '14 at 07:20

1 Answers1

1

Yes, simply write

throws new ExceptionType(parameter);

where ExceptionType is the name of the custom exception class.