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.