I have the following code in the 'main' method:
static void Main(string[] args)
{
try
{
int a = 0;
int b = 5;
b /= a;
}
catch (MyException ex)
{
Console.WriteLine(ex.Message)
}
}
And MyException class is as the following:
public class MyException : Exception
{
public MyException()
{
}
}
The program breaks on b /= a;
whereas I'm expecting it to go to the catch
command.
If I replace MyException
with Exception
, the exception is caught and the program doesn't break.
How can I catch a custom exception?
As mentioned in the comments the problem is not that you can't catch your exception, the problem is that the code isn't throwing that type of exception. It throws a System.DivideByZeroException
. If you want to test your code to see it catch your exception then just replace b /= a;
with throw new MyException();
and you will see it catch your exception. It catches something when you use the base class Exception
because the DivicdeByZeroException
also inherits from Exception
.
Keep in mind the only way your exception will ever be thrown is if you have the line throw new MyException();
somewhere. You can make all the custom exceptions you want but .NET libraries aren't going to just start throwing them for you. In this case you shouldn't even be using a custom exception, if this is a learning exercise that's fine but it just doesn't really make sense when you already have an informative exception being thrown.