ADVERTISEMENT
ADVERTISEMENT

Java program to handle Number Format Exception

Java example to handle Number Format Exception.
Submitted by Nidhi, on April 17, 2022

Problem Solution:

In this program, we will handle a Number Format Exception using try, catch block. The code that may generate an exception should be written in the "try" block, and the "catch" block is used to handle the exception and prevent program crashes.

Program/Source Code:

The source code to handle Number Format Exception is given below. The given program is compiled and executed successfully.

// Java program to handle Number Format 
// Exception

public class Main {
  public static void main(String[] args) {
    try {
      String str = "xyz";

      int num = Integer.parseInt(str);

      System.out.println("Number is: " + num);
    } catch (NumberFormatException e) {
      System.out.println("Exception: " + e);
    }
    System.out.println("Program Finished");
  }
}

Output:

Exception: java.lang.NumberFormatException: For input string: "xyz"
Program Finished

Explanation:

In the above program, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program.

Here, we created "try" and "catch" blocks. In the "try" block, a number format exception gets generated because we tried to convert the non-numeric string str into an integer. Here, we handled generated exceptions using the "catch" block and printed exception message.

Java Exception Handling Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.