Difference between Catch (Exception) and Catch (Exception ex)

What is the difference between Catch(Exception) and Catch(Exception ex) . I see that both give me the expected result. Then what is the difference? Which one is recommended?

Assume the code is below.

 int a = 1, b = 0; try { int c = a / b; Console.WriteLine(c); } 

Which of the following catch blocks is recommended? What is the actual difference between the two?

 catch (Exception ex) { Console.WriteLine(ex.Message); } 

OR

 catch (Exception) { Console.WriteLine("Oh NO!!"); } 
+6
source share
6 answers

Well, catch(Exception ex) same as catch(Exception) with only one difference: in catch(Exception ex) we have access to the exception class (cause of error) example. Usually you need an instance of an exception class to print the original message:

  try { ... } catch (AppServerException e) { Console.WriteLine("Application server failed to get data with the message:"); Console.WriteLine(e.Message); // <- What actually got wrong with it } 

Unless you need an instance of an exception class, for example. you plan on simply consuming an exception, the catch (Exception ex) syntax is excessive and the 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 the general class of exceptions without passing again:

  try { int c = a / b; } catch (Exception) { // <- Never ever do this! Console.WriteLine("Oh NO!!"); } 

Do you really want to code "any error (green smoke from the CPU turned on) happend just print" Oh No and continue "? A template with an Exception class is something like this:

  tran.Start(); try { ... tran.Commit(); } catch (Exception) { // Whatever had happened, let first rollback the database transaction tran.Rollback(); Console.WriteLine("Oh NO!"); throw; // <- re-throw the exception } 
+3
source

It is pretty simple:

  • in the first code, you can catch the exception and get the object representing it in order to have more information about what happened.
  • in the second code, you only know that an exception was thrown, but you have no additional information about this.

What to use actually depends on how much information you want about the exception.

+3
source

If you need to use an exception inside a catch , give Exception name; otherwise, keep it anonymous.

There are situations where a catch should do more than just show an exception message. For example, when you encounter exceptions for an application, you can examine the additional elements of an 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 ConnectToServerException custom exception has a property called AttemptedConnectionServerName with the name of the server you tried to connect to, and an AllowedServerNames enumeration AllowedServerNames with the names of available servers.

There are also situations where all you need to know is that only an exception of a certain type has occurred. In this case, you do not need to specify a named variable.

+2
source

Catch (Exception) does the same as the Exception type.

Catch (Exception ex) catches all exceptions and, in addition, you can receive a message through its link.

The use depends on the requirement, if you want to show an exception message, you have the option to use ex.Message otherwise Catch (Exception) will be enough.

0
source

With catch(Exception) you will only indicate which exception you are going to handle in this catch block (in this case, any exception that was raised, so it will be the same as catch only)

With catch(Exception ex) you pass an instance of the actual exception that is thrown, so you can access the properties of the exception and do something with the information provided.

0
source

The difference is that the attempt "Division by zero attempt" will be printed. and the other will print Oh NO !!.

Exception handling is a complex issue and is application dependent, but there are a few general notes here:


Generally speaking, it is best to provide handlers for certain exceptions:

Sort of:

  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 simply not enough and you will have to use a logger to make better use of it before.


Ideally, if you decide to give the user unprocessed error messages, you should print all the messages in the exception chain, or at least the deepest ones.

Sort of:

  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() } 
0
source

Source: https://habr.com/ru/post/951493/


All Articles