There's two topics I want to talk about.
The Overly broad catch and Wrapping APIs that don't use Exceptions. (Such as some websphere/java services I've been working with lately)
It’s a pandemic in most of the code I look at where I work. Nothing against the developers I work with. We inherited this code and we’ve been copying and pasting our way to glory because “if it works don’t fix it”
I got into this all-time religious war with one of my co workers today because he was catching System.Exception and returning false within a method. I asked why, and he said because he wanted to make sure to return false if anything failed.
This article would have helped me explain better why you shouldn’t catch system.exception
The basic premise is that when you catch System.Exception you’re catching everything that could possibly happen. So when your program doesn’t work the way you expect it should, you have to go deep diving into the debugger to find out what is getting caught in the exception handler (or log every single exception that gets to there in some giant log file that becomes a dumping ground for random BS and garbage)
So the other topic. Wrapping code that doesn't throw exceptions.
How many times have you seen code like this:
Int returnCode = Foo(out myparam1, out param2);
If(returncode != 0)
{
//do stuff
}
Else if(returncode == 3)
{
//do other stuff
}
Else
{
//an error happened, log stuff and exit.
}
YUCK! J
Ideally you’d want something like this
Try
{
Foo(out myParam1, out myParam2);
//do stuff
}
Catch(Exception3 ex)
{
//do other stuff
}
//all other errors bubble up to the main program.
So anyhow, how do we get to something like this if we have an API that uses error codes?
Just wrap it and throw exceptions. Preferably custom exceptions that are descriptive (unlike mine that are named genericly for example purposes)! J
Public void foo(out int param1, out int param2)
{
Int code = foo(out param1, out param2);
If(code != 0) return;
If(code == 3) throw new MyCustomException(“Code was 3”);
Else throw new MyCustomGeneralException(“A bad thing happened, error code was: “+code.ToString() );
}
Public class MyCustomException : System.Exception{}
Public class MyCustomGeneralException : System.Exception{}
Anyhow, try this out and see if it helps your code read better and flow smoother.