JohnyMotorhead JohnyMotorhead - 3 months ago 29
C# Question

Returning a custom exception

I am trying to implement my own Exception class in C#. For this purpose I have created a CustomExecption class derived from Exception.

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) { }
}


Then I use it

static void Main(string[] args)
{
try
{
var zero = 0;
var s = 2 / zero;
}
catch (CustomException ex)
{
Console.Write("Exception");
Console.ReadKey();
}
}


I'm expecting I will get my exception but all I get is a standard DivideByZeroException. How can I catch a divide by zero exception using my CustomException class? Thanks.

Answer

You can't magically change type of exception thrown by existing code.

You need to throw your exception to be able to catch it:

try 
{
       try
        {
            var zero = 0;
            var s = 2 / zero;
        }
        catch (DivideByZeroException ex)
        { 
            // catch and convert exception
            throw new CustomException("Divide by Zero!!!!");
        }
    }
    catch (CustomException ex)
    {
        Console.Write("Exception");
        Console.ReadKey();
    }