0

My practice for over a year now is to provide a separate try/catch block for each method i am writing then throwing the Exception Object should a specific block of code fail. For Example:

void MainMethod()
{
    try {
        int num = Method1();
        string str = Method3();
        bool bln = Metho4();
    } catch (Exception Ex) {
        MessageBox.Show(Ex.Message);
    }
}

int Method1() {
    try {
        return 123 + Method2();
    } catch (Exception) {
        throw;
    }
}

int Method2() {
    try {
        return Convert.ToInt32("One Hundred"); // <-- Obviously would fail.
    } catch (Exception) {
        throw;
    }
}

string Method3() {
    try {
        string str1 = "Hello ";

        return str1 + 12345; // <-- Would also fail.
    } catch(Exception) {
        throw;
    }
}

bool Method4() {
    try {
        return true;
    } catch(Exception) {
        throw;
    }
}

Should i provide each and every method their own/separate try/catch blocks? Or would it be better if its just the Main Method that has the try/catch?

Thanks

Nii
  • 450
  • 6
  • 25
  • It depends on how you want to handle your exceptions. – SᴇM Sep 25 '17 at 05:30
  • In the case of your example, you can only use `MainMethod`'s block. – SᴇM Sep 25 '17 at 05:33
  • As per my opinion, i would go with only `try/catch` within `MainMethod()`. – mmushtaq Sep 25 '17 at 05:33
  • I would suggest to have a try catch block on your main method, however I would recommend to put your logic instead of leaving it to try catch and waiting for exception to raise. Checking for null objects or try cast while conversion etc. can be use efficiently. – kashi_rock Sep 25 '17 at 05:39
  • that would only be if the sub-methods are doing some sort of arithmetic or minor process right? If they were accessing the Data Access Layer and with respect to using Database Transactions, that is where nested `try/catch` blocks would benefit right? i mean, rolling back transactions have to take place on the Catch Block. – Nii Sep 25 '17 at 05:41
  • Only catch exceptions where they're expected, and/or where there's something to do when they're encountered. It's pointless to just have a `throw` inside a `catch`, with no other code to log what happened, or cleanup data, or state, or *something* to react to the exception. And if you don't know what to do, then let the exception bubble up on it's own until it reaches some method that *does* know what to do (or it reaches the user and they log a bug). Note that one `catch` may do something and then re-throw, and another `catch` may do something else in reaction to that. – Rufus L Sep 25 '17 at 06:29
  • Also mind that try/catch is doing more than the obvious. There's a context created for each try/catch block, so scattering try/catch all over the place will sooner or later impact performance for close to no benefit. It also makes the code less readable (by adding "noise"). – Fildor Sep 25 '17 at 07:04

1 Answers1

2

It really depends on what you're trying to accomplish. I prefer to catch and handle at the 'root' level whenever possible.

In your case I would use try/catch in the MainMethod and only try/catch anywhere else if I would like to catch and handle a specific exception and possibly recover.

Dan D
  • 2,493
  • 15
  • 23
  • 1
    i see, as per my example - i can also clearly decide to just provide a single try/catch on the `MainMethod`. However, i was thinking, if these "Sub" Methods were working on a Data Access Layer specially concerning Database Transactions, that is where nested try/catch will benefit, assuming that i'll Rollback the transaction on the Catch Block. Am i right? – Nii Sep 25 '17 at 05:40
  • Going from your example, correct. Or potentially if you're running in AWS, Azure, etc you may want to catch a specific Connection exception type and use a retry system to establish a connection – Dan D Sep 25 '17 at 05:44
  • Then provide `try/catch` within `DAL` method as well and if any exception occurred then rollback your transaction and throw exception. i.e. `catch(Exception exp){ db.Rollback(); throw exp; }` . This exception would be catch in `MainMethod`. – mmushtaq Sep 25 '17 at 05:46
  • Remember when re-throwing an exception do not use `throw exp;` but use `throw;` instead. Otherwise your call-stack will be incorrect – Dan D Sep 25 '17 at 05:47
  • what are the complications of using `throw exp;` instead of `throw;` ? i mean, is the difference really that big? – Nii Sep 25 '17 at 08:09
  • `throw exp` will make it appear as if the line `throw exp` was the location of the original exception. If you had several nested function calls in your `try` bock, your stack trace would show the error was in your `catch`. https://stackoverflow.com/questions/730250/is-there-a-difference-between-throw-and-throw-ex – Dan D Sep 25 '17 at 12:16