This is a simple example
[Serializable]
public class MyException : Exception
{
public MyException() { }
public MyException( string message ) : base( message ) { }
public MyException( string message, Exception inner ) : base( message, inner ) { }
protected MyException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context ) : base( info, context ) { }
}
class Program {
static void Main(string[] args) {
try{
throw new MyException("Whoops#1");
//throw new MyException("Fubar#2");
}catch(MyException myEx){
string aExMsg = myEx.Message;
if (aExMsg.Contains("#1")){
Console.WriteLine("Whoops was caught");
}
if (aExMsg.Contains("#2")){
Console.WriteLine("Fubar was caught");
}
}catch (Exception ex){
throw;
}
Console.Write("Press <ENTER> to continue...");
Console.ReadLine();
}
}
Uncomment the line //throw new MyException("Fubar#2");
and run it, the catch
block for MyException
will trap the error, examine the contents of the Message
class, looking for a specific clue, and thus can get an instance.
However, it is imperative to note, this is not exactly a good way of handling exceptions, or controlling the flow of code by doing this. Don't care or even go down the road in determining what instance is it - why? too much time expended there! Just look at the Message
part for a clue and leave it at that.
Exceptions, are for a reason, when a error condition occurs, two outcomes - to catch them or quietly discard (bad!).
Looking at the above example code, if that is part of a processing data in some shape or form, does it impact the soon-to-be-yet-executed dependency class or method?
Set off a couple of trip switch flags for benefit of soon-to-be-yet-executed dependency class or method in such a way, that when further code beyond gets executed; it will see the trip switch flag that is set previously, to skip out on bunch of code, knowing that an error occurred previously, will make things worse.
Finally, gracefully log it, inform the operator Just don't use the word ERROR in some popup or component that the operator will see, it will just give them a un-needed panic and stress.