c# - How to Catch Custom Exception -
i have following code in 'main' method:
static void main(string[] args) { try { int = 0; int b = 5; b /= a; } catch (myexception ex) { console.writeline(ex.message) } }
and myexception class following:
public class myexception : exception { public myexception() { } }
the program breaks on b /= a;
whereas i'm expecting go catch
command. if replace myexception
exception
, exception caught , program doesn't break.
how can catch custom exception?
as mentioned in comments problem not can't catch exception, problem code isn't throwing type of exception. throws system.dividebyzeroexception
. if want test code see catch exception replace b /= a;
throw new myexception();
, see catch exception. catches when use base class exception
because divicdebyzeroexception
inherits exception
.
keep in mind way exception ever thrown if have line throw new myexception();
somewhere. can make custom exceptions want .net libraries aren't going start throwing them you. in case shouldn't using custom exception, if learning exercise that's fine doesn't make sense when have informative exception being thrown.
Comments
Post a Comment