Convert/Cast a String to Int/Number with try/catch exception in Java

If you want to set a default number in case of Parsing failure, you can catch an exception and set the default value in Java as shown below.

String bar = "12345";

int foo;
try {
   foo = Integer.parseInt(bar);
catch (NumberFormatException e) {
   foo = 100;

Explanation: We have a variable here named bar with the value of 12345 as a string. We create a variable named foo and set its data type to integer by adding key int. Then we tried to parse a string to an integer in the try block. We set the default value of 100 to this variable in the catch block if the code in try block fails.

Leave a Reply

Your email address will not be published. Required fields are marked *