Is there any drawback to putting most of your code for your function in a try statement
. If I do something that requires a try statement
, I usually end up doing a lot of work for that function inside the try statement because I usually declare my variables in there and can't use them outside that scope if I do that. Is this common and accepted? Do people usually declare variable before without initializing them so they're not doing everything (including calls to other functions) inside a try statement
? Or does it not matter if it's very long?
A method should do one thing and do it good. In this case your method is doing two things: business logic and error handling:
public Foo bar() {
try {
//business logic that may throw
//...
//end even more
} catch(BuzzException e) {
//Error handling
}
}
Very often I find myself extracting the contents of try
block into a separate method without error handling:
public Foo bar() {
try {
return unsafeBar();
} catch(BuzzException e) {
//Error handling
}
}
public Foo unsafeBar() throws BuzzException {
//business logic that may throw
//...
//end even more
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With