A catch
clause without arguments can catch any type of exception. This is sometimes referred to as the "general" catch clause. You should probably never use this in a production application, but I suppose it might sometimes be useful for debugging. It looks like this:
catch
{
}
A catch
clause can also specify the particular exception class that you want to catch. You should always do this in your applications because you're only supposed to catch exceptions that you know how to handle. For example, you might want to catch a DivideByZeroException
; you'd do it like this:
catch (DivideByZeroException)
{
}
Of course, that has the side effect that you're unable to refer to the exception class itself inside of the catch
block because you haven't assigned it to a variable. If you need to call properties or methods on the instance of the exception class that you catch, you'll need to include a named variable in the catch
statement. That is probably what you're most used to seeing, and it looks like this:
catch (DivideByZeroException ex)
{
// do something with ex here
}
Then there are two ways to write the throw()
statement, and it matters which one you choose:
The first just looks like this:
throw;
It is written without any arguments, and the purpose is to rethrow the caught exception while preserving the stack trace and as much information about the original exception as possible.
(There are still some edge cases where this can cause you to lose the stack trace, but generally this is much preferred over the alternative below.)
The second option passes an instance of an exception class as an argument, and looks like this:
throw(ex);
or this:
throw ex;
This also rethrows the specified exception, but as mentioned above, it has the downside of losing some of the stack trace information that tells you what method was responsible for throwing the exception. It's rare that you'll use this except to throw a new exception object that you create in the same method.
For example, if you wanted to catch a low-level exception and wrap it within a new exception object for consumption by a higher-level function, you would use this form.