Sometimes you need to change an exceptions type (usually to a custom
exception type) but still want to maintain stacktrace information (read
about this issue in part1). Well it is really easy just look at this
example
1
2 Public Sub Layer2()
3 Throw New NotImplementedException
4 End Sub
5
6 Public Sub LogError(ByVal ex As Exception)
7 'TODO: log the error
8 End Sub
9
10 Private Sub Layer1()
11 Try
12 Layer2()
13 Catch ex As Exception
14 Throw New CustomException("Layer1 error", ex)
15 End Try
16 End Sub
17
18 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
19 Try
20 Layer1()
21 Catch ex As Exception
22 LogError(ex)
23 Throw
24 End Try
25 End Sub
By throwing a new exception and adding the caught exception as the inner exception we maintain the stacktrace information.
FYI my stack output looks like this:
System.Exception: Layer1 error ---> System.NotImplementedException: The method or operation is not implemented.
at WindowsApplication1.Form1.Layer2() in C:\...\Form1.vb:line 3
at WindowsApplication1.Form1.Layer1() in C:\...\Form1.vb:line 12
--- End of inner exception stack trace ---
at WindowsApplication1.Form1.Layer1() in C:\..\Form1.vb:line 14
at WindowsApplication1.Form1.Button1_Click(Object sender, EventArgs e) in C:\..\Form1.vb:line 20you
can see that the inner exception has all the trace information down to
where the original exception occured but the outer exception shows only
that at Layer1() did an exception occur.