Skip to content

Instantly share code, notes, and snippets.

@bahmanm
Created June 20, 2023 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahmanm/85e4c6224a7c940d8d1b874e7d6dff09 to your computer and use it in GitHub Desktop.
Save bahmanm/85e4c6224a7c940d8d1b874e7d6dff09 to your computer and use it in GitHub Desktop.
Nested or sequential try-catch blocks?
/**
* Using nested try-catch blocks.
*
* @param str a string representing an integer
* @return smallest integer type or null
*/
Number atoi_NestedTryCatch(String str) {
try {
return Integer.valueOf(str);
} catch (NumberFormatException ignore1) {
try {
return Long.valueOf(str);
} catch (NumberFormatException ignore2) {
try {
return new BigInteger(str);
} catch (NumberFormatException ignore3) {
return null;
}
}
}
}
/**
* Using sequential try-catch blocks.
*
* @param str a string representing an integer
* @return smallest integer type or null
*/
Number atoi_SequentialTryCatch(String str) {
try {
return Integer.valueOf(str);
} catch (NumberFormatException ignore1) {}
try {
return Long.valueOf(str);
} catch (NumberFormatException ignore2) {}
try {
return new BigInteger(str);
} catch (NumberFormatException ignore3) {}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment