NumberFormatException एक unchecked exception है जो parseXXX() मेथड्स द्वारा फेंका जाता है जब वे एक स्ट्रिंग को संख्या में फॉर्मेट (कन्वर्ट) करने में असमर्थ होते हैं।
NumberFormatException को java.lang पैकेज के क्लासेस में कई मेथड्स/कंस्ट्रक्टर्स द्वारा फेंका जा सकता है। उनमें से कुछ निम्नलिखित हैं:
- public static int parseInt(String s) throws NumberFormatException
- public static Byte valueOf(String s) throws NumberFormatException
- public static byte parseByte(String s) throws NumberFormatException
- public static byte parseByte(String s, int radix) throws NumberFormatException
- public Integer(String s) throws NumberFormatException
- public Byte(String s) throws NumberFormatException
प्रत्येक मेथड के लिए स्थितियाँ परिभाषित हैं जहाँ यह NumberFormatException फेंक सकता है। उदाहरण के लिए, public static int parseInt(String s) throws NumberFormatException तब जब:
- स्ट्रिंग s null है या s की लंबाई शून्य है।
- यदि स्ट्रिंग s में नॉन-न्यूमेरिक कैरेक्टर्स हैं।
- स्ट्रिंग s का मान एक Integer को रिप्रेजेंट नहीं करता।
उदाहरण 1
public class NumberFormatExceptionTest {
public static void main(String[] args){
int x = Integer.parseInt("30k");
System.out.println(x);
}
}
आउटपुट
Exception in thread "main" java.lang.NumberFormatException: For input string: "30k"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at NumberFormatExceptionTest.main(NumberFormatExceptionTest.java:3)
NumberFormatException को कैसे संभालें
हम NumberFormatException को दो तरीकों से संभाल सकते हैं:
- उस कोड के चारों ओर try और catch ब्लॉक का उपयोग करें जो NumberFormatException का कारण बन सकता है।
- अपवाद को संभालने का दूसरा तरीका throws कीवर्ड का उपयोग है।
उदाहरण 2
public class NumberFormatExceptionHandlingTest {
public static void main(String[] args) {
try {
new NumberFormatExceptionHandlingTest().intParsingMethod();
} catch (NumberFormatException e) {
System.out.println("हम NumberFormatException को पकड़ सकते हैं");
}
}
public void intParsingMethod() throws NumberFormatException{
int x = Integer.parseInt("30k");
System.out.println(x);
}
}
उपरोक्त उदाहरण में, मेथड intParsingMethod() उस अपवाद ऑब्जेक्ट को फेंकता है जो Integer.parseInt("30k") द्वारा फेंका जाता है, अपने कॉलिंग मेथड को, जो इस केस में main() मेथड है।
आउटपुट
हम NumberFormatException को पकड़ सकते हैं