如果我们想要把某些字符串转化为数字,就需要使用到Integer.parseInt(str)
方法了,
public class ExceptionTest3 {
public static void main(String[] args) {
int num = getInt("20");
System.out.println(num);
}
// 字符串转换为数字
public static int getInt(String str) {
return Integer.parseInt(str);
}
}
运行结果
如果我们传入的参数是“小王”,那么将会抛出一个异常,如下:
java中常见的异常类
IOException
操作输入流和输出流可能出现的异常。
ArithmeticException
数字异常,如果把整数除以0,就会抛出这个异常,
int a=12/0; // 抛出ArithmeticException
NullPointerException
空指针异常,当引用变量为null时,访问对象的属性和方法,就会抛出这个异常。
String d = null;
System.out.println(d.length()); // 抛出NullPointerException
标题ArrayIndexOutOfBoundsException
下标异常,一般出现在数组中
int[] array = new int[4];
array[0]=1;
array[7]=1;// 抛出 ArrayIndexOutOfBoundsException
标题ClassCastException
当类型转化失败是就会出现这种异常。
ILLegalArgumentException
非常参数异常,可以用来检查方法的参数是否合法。