Nested Exception Checking

If an error occurs in a called procedure, can that exception be passed back?

I created a test project to see if I return the except if that will be caught in the CallOne Try statement but it doesn't.

I guess I could put the CallOne() inside of an if statement.  Any suggestions?

Public Class Form1
   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      CallOne()
      End
   End Sub

   Private Sub CallOne()
      Try
         CallTwo()

         'Rest of code which shouldn't execute if CallTwo has an exception.
         MessageBox.Show("Merry Christmas")
      Catch ex As Exception
         MessageBox.Show("1:" & ex.Message)
      End Try
   End Sub

   Private Function CallTwo() As Exception
      Dim ex As Exception = Nothing

      Try
         Throw New Exception("Test Error")
      Catch ex
         MessageBox.Show("2:" & ex.Message)
      End Try

      Return ex
   End Function
End Class

Open in new window

BC_EasyriderAsked:
Who is Participating?
 
Reza RadConnect With a Mentor Consultant, TrainerCommented:
this code will show first messagebox from sub CallTwo then second as Merry christmas,
if you want to go to catch block of sub CallOne when you hit an exception in callTwo , you must throw an exception in sub CallTwo and catch block like below, or don't use it in try-catch in sub CallTwo.

Public Class Form1
   Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      CallOne()
      End
   End Sub

   Private Sub CallOne()
      Try
         CallTwo()

         'Rest of code which shouldn't execute if CallTwo has an exception.
         MessageBox.Show("Merry Christmas")
      Catch ex As Exception
         MessageBox.Show("1:" & ex.Message)
      End Try
   End Sub

   Private Function CallTwo() As Exception
      Dim ex As Exception = Nothing

      Try
         Throw New Exception("Test Error")
      Catch ex
         Throw New Exception(ex.Message)
      End Try

      Return ex
   End Function
End Class


0
 
BC_EasyriderAuthor Commented:
This makes complete sense.  I'm not sure if what I'm trying to do it good coding practice but I'm trying to simplify my code when an error occurs.  There's no sense sometimes for the calling procedure to continue on if there's an error.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.