Created
June 20, 2023 23:30
-
-
Save bahmanm/85e4c6224a7c940d8d1b874e7d6dff09 to your computer and use it in GitHub Desktop.
Nested or sequential try-catch blocks?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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