I was asked about try-catch blocks if we use them in multilevel methods (one’s calling another that throws exception -> which catch block will catch it, etc.). Here I show you a simple, 3 level try-catch block.
We have a button that has Click event (1. level), that calls the SecondLevelMethod() 2. level method, that calls the ThirdLevelMethod(). In this last method we throw an exception.
The main code is here, let’s walk through.
private void button1_Click(object sender, EventArgs e) { try { SecondLevelMethod(); } catch (Exception ex) { MessageBox.Show(ex.Message, "1. level - All Exception"); } } private void SecondLevelMethod() { try { ThirdLevelMethod(); } catch (ArgumentException ex) { MessageBox.Show(ex.Message, "2. level - Argument Exception"); } catch { throw; } } private void ThirdLevelMethod() { try { throw new FormatException("My exception"); } catch (DuplicateNameException ex) { MessageBox.Show(ex.Message, "3. level - Duplicate Name Exception"); } catch { throw; } }
As you can see, we simulate an exception throwing in the 3. level. This exception is now a FormatException. As far as this catch block catches only DuplicateNameException, it gets into the last catch block, that throws one level higher.
Now on this level we also don’t have this kind of catch:
catch (FormatException fex) { }
So the last catch block will catch it, that also throws one level higher. Now, we are in our Click event that has the ‘ultimate’ catch block:
catch (Exception ex) { }
This one catches every kind of exception as far as this is the inheritable parent class. 🙂
By pressing the button on the form, you’ll get this message:
If you change the throw new line to
throw new ArgumentException("My exception");
it will be caught in SecondLevelMethod(), because it has a catch block with ArgumentException:
Unhandled exception may occur in this case, if don’t have try-catch block in our Click event method, so none will catch the exception, it won’t be handled, so it’ll be unhandled exception. That’s all.
Unhandled exception in runtime: