Overriding the message of exception in C# -


is there way override message of exception?
don't want make custom exception override message of existing exception.
example: every time when argumentoutofrangeexception thrown, i'd contain message instead of default one.

is possible?

for exceptions you're throwing, can pass message in constructor:

throw new argumentoutofrangeexception("name", "my custom message"); 

note here, name name of parameter caused problem. in c# 6, should use nameof operator make refactoring-safe:

public void foo(int x) {     if (x > 10)     {         throw new argumentoutofrangeexception(nameof(x), "that's big");     } } 

you can't modify message of exception thrown other code, can catch exception , rethrow one:

try {     ... } catch (fooexception e) {     // keep original exception     throw new barexception("some message", e); } 

i try avoid doing though. if you're considering showing exception messages users, shy away - they're aimed @ developers. example, argumentoutofrangeexception suggested should indicate bug in code rather external condition (like network failure or whatever) - user isn't going able bug; it's should fix. network failure or similar @ least more reasonable user take action about, frankly it's not going clear chain of events is.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -