Friday, April 3, 2009

Visual Studio CSharp - Exception tips?

You can catch the type 'Exception' and EVERY exception will be caught. If you want to handle multiple exceptions in a different way, you could catch specific exceptions.
For example
try{ ... }
catch(FileNotFoundException ex)
{ // add some code that will create a default file }
catch(ArgumentException ex)
{ // add different code to handle this exception }
catch(Exception ex)
{ // do something with the rest of the exceptions }

In the above example, if a FileNotFoundException occurs, the first catch clause will run, and if some unknown exception occurs that you didn't see coming, it will be caught in the last clause (Exception ex).

No comments: