Frage

I am not sure if this is at all possible. (I think it should). Would it be possible to catch a customexception without throwing new one as follows?

        try
        {
            //Some logic which throws exception
        }
        catch (Exception)
        {
            throw new CustomException();
        }

What I would like to have is as follows:

        try
        {
            //Some logic which throws exception
        }
        catch (CustomException)
        {
            // Handles the exception
        }

I have tried the above but its not catching my CustomException directly. I have to do "throw new CustomException()" which is not ideal. What am I doing wrong?

My custom exception class looks like as follows:

 [Serializable]
    public class CustomException : Exception
    {
        public CustomException()
            : base() { }

        public CustomException(string message)
            : base(message) { }

        public CustomException(string format, params object[] args)
            : base(string.Format(format, args)) { }

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

        public CustomException(string format, Exception innerException, params object[] args)
            : base(string.Format(format, args), innerException) { }

        protected CustomException(SerializationInfo info, StreamingContext context)
            : base(info, context) { }
    }

Thanks,

War es hilfreich?

Lösung

The catch clause will not automatically convert exceptions, it is not the way it works. It will filter the exception that gets thrown in the try clause. By using

catch (CustomException e)
{
}

you are handling only CustomException instances or instances of derived exception clasess - in other words the catch clause will be executed only if the try block throws any of those. So, if for instance a FileNotFoundException gets thrown, your catch clause will not get executed and code will result in an unhandled FileNotFoundException.

If your intention is to make your code throw only CustomException for all possible exceptions that might occur in the try block, you need to catch all of them. A general catch block will do this for you:

catch (Exception e) // catches exceptions of any type
{
    throw new CustomException(e.Message, e);
}

Note that we pass the original exception in the CustomException constructor (message is optionally reused, you may put your own). This is an often omitted but very important practice, because by passing the inner exception you will have a complete stack-trace in the logs, or better information for the problem when debugging.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top