Reputation: 5957
What is the difference between Catch(Exception)
and Catch(Exception ex)
. I can see both giving me expected output. Then what is the actual difference ? Which one is recommended ?
Suppose the code is below.
int a = 1, b = 0;
try
{
int c = a / b;
Console.WriteLine(c);
}
Which of the below catch block is recommended to use ? What is the actual difference between those ?
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
OR
catch (Exception)
{
Console.WriteLine("Oh NO!!");
}
Upvotes: 10
Views: 27559
Reputation: 186698
Well, catch(Exception ex)
is just the same as catch(Exception)
with one difference
only: in catch(Exception ex)
we have an access to the exception class (error cause)
instance. Usually you need an exception class instance to print out the original
message:
try {
...
}
catch (AppServerException e) {
Console.WriteLine("Application server failed to get data with the message:");
Console.WriteLine(e.Message); // <- What's actually got wrong with it
}
If you don't need the exception class instance, e.g. you plan just to consume the exception, the catch(Exception ex) syntax is excessive and catch(Exception) is prefferable:
try {
c = a / b;
}
catch (DivideByZeroException) {
c = Int.MaxValue; // <- in case b = 0, let c be the maximum possible int
}
Finally. Do not catch a general Exception class without re-throwing:
try {
int c = a / b;
}
catch (Exception) { // <- Never ever do this!
Console.WriteLine("Oh NO!!");
}
Do you really want to code "whatever error (green fume from CPU included) had happened just print out 'Oh No' and continue"?
The pattern with Exception class is something like this:
tran.Start();
try {
...
tran.Commit();
}
catch (Exception) {
// Whatever had happened, let's first rollback the database transaction
tran.Rollback();
Console.WriteLine("Oh NO!");
throw; // <- re-throw the exception
}
Upvotes: 6
Reputation: 35027
The difference is that one will print Attempted to divide by zero. and the other will print Oh NO!!.
Handling exceptions is a complex problem and depends on the application, but here are few general comments:
Generally speaking it's best to provide handlers for specific exceptions:
Something like:
catch ({System.DivideByZeroException ex )
{
Console.WriteLine("Ops. I cannot divide by zero." );
}
catch ({System.Exception ex )
{
Console.WriteLine("There was an error during calculations: {0}", ex.Message );
}
Sooner or later you will find out that Console.WriteLine
is just not good enough and you will have to use a logger so best to start using it early.
Ideally, if you decide to expose raw error messages to the user, you should be printing all messages in the exception chain or at least the one which is most deep.
Something like:
catch ({System.DivideByZeroException ex )
{
Console.WriteLine("Oops. I cannot divide by zero." );
}
catch ({System.Exception ex )
{
Console.WriteLine(GetExceptionMsgs(ex));
}
...in another class...
public static string GetExceptionMsgs(Exception ex) {
if( ex == null ) {
return "No exception = no details";
}
var sb = new StringBuilder();
while( ex != null ) {
sb.AppendLine(ex.Message);
ex = ex.InnerException;
}
return sb.ToString()
}
Upvotes: 0
Reputation: 3481
Catch (Exception)
do the same thing, as it is also a Exception
type.
Catch (Exception ex)
catches all exceptions and in addition you can retrieve message through its reference.
Use is dependent on requirement, if you want to show exception message you have facility to use ex.Message
otherwise Catch (Exception)
will be enough.
Upvotes: 0
Reputation: 726599
If you need to use the exception inside the catch
block, give Exception
a name; otherwise, keep it anonymous.
There are situations when the catch
block needs to do more than simply show exception's message. For example, when you catch application-specific exceptions, you may be able to examine additional elements of the exception object. Here is a hypothetical example:
catch (ConnectToServerException cse) {
MessageBox.Show(string.Format(
"Connection to server '{0}' failed. Use a name from the following list: {1}"
, cse.AttemptedConnectionServerName
, string.Join(", ", cse.AllowedServerNames)
));
}
The above code assumes that the custom exception ConnectToServerException
has a property called AttemptedConnectionServerName
with the name of the server to which you tried to connect, and an enumeration property AllowedServerNames
with the names of available servers.
There are also situations when all you need to know is that an exception of a particular type just happened. In this case, you do not need to provide a named variable for it.
Upvotes: 3
Reputation: 2047
With catch(Exception)
you only specify what kind of exception you're gonna handle in that catch block (in this case, any exception that is raised, so it would be the same as just catch
)
With catch(Exception ex)
you pass an instance of the actual exception that is raised, so you can access the properties of the exception and do something with the information provided.
Upvotes: 0
Reputation: 3105
It's quite simple:
What to use actually depends on how much information you want to have about the exception raised.
Upvotes: 3