如何在Java中處理NumberFormatException(非受檢異常)?
NumberFormatException是一個非受檢異常,當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為空或s的長度為零。
- 如果字串s包含非數字字元。
- 字串s的值不能表示為整數。
示例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("We can catch the NumberFormatException");
}
}
public void intParsingMethod() throws NumberFormatException{
int x = Integer.parseInt("30k");
System.out.println(x);
}
}在上面的例子中,方法intParsingMethod()將Integer.parseInt(“30k”)丟擲的異常物件拋給它的呼叫方法,在本例中是main()方法。
輸出
We can catch the NumberFormatException
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP