Rafa Gomez
Rafa Gomez

Reputation: 710

Exception Handling Best-Practice

If I call two methods that can throw the same exceptions after each other, but the ground of the exception is different, how should I handle it?

Should I put a try catch block around each of those methods, so that I can handle both exceptions in a different way or how I can get the method that throws the exception?

As example: I have this method

dir = Directory.CreateDirectory(Path.Combine(My.Settings.CalibrationExcelExportPath, dirName)) 

The method can throw an IOexception.

Next I call a method ExcelExport.ExportCalibrationAsync that creates a TempFile, which also can throw an IOexception,if for example no more temp names free.

Now I want to handle the exception in a diff. way to give the proper information to the user.

I've tried with exception.TargetSite but I get both times Void WinIOError(Int..) so I can't use that to distinguish.

What's the best practice here

Upvotes: 2

Views: 387

Answers (2)

Jan Muncinsky
Jan Muncinsky

Reputation: 4408

I would suggest you to create your custom exceptions, because your call stack may be deep and you may have a handler in different method from that one where the exception is coming from.

Try
    dir = Directory.CreateDirectory(Path.Combine(My.Settings.CalibrationExcelExportPath, dirName
Catch ex As Exception
    Throw New CreateDirectoryException("An exception has occurred when creating a directory.", ex)
End Try

Try
    ' Other code causing exception here
Catch ex As Exception
    Throw New AnotherException("An exception has occurred.", ex)
End Try

Than create whatever handler you like for CreateDirectoryException and AnotherException.

Upvotes: 2

Fabulous
Fabulous

Reputation: 2423

There are two ways I'll talk about of doing it. One is to nest your Try...Catch blocks. But I would recommend the second which I have detailed below.

My assumption here is that if the call you specified is successful, dir will have a value and if not, it will be Nothing. If that is the case, you can do your exception handler selectively as follows:

Try
    dir = Directory.CreateDirectory(Path.Combine(My.Settings.CalibrationExcelExportPath, dirName))
    ' Other code here that might throw the same exception.
Catch ex As IOException When dir Is Nothing
    ' Do what you need when the call to CreateDirectory has failed.
Catch ex As IOException When dir Is Not Nothing
    ' For the other one. You can leave the when out in this instance
Catch ex As Exception
    ' You still need to handle others that might come up.
End Try

Upvotes: 3

Related Questions