java中常见异常的举例说明

//ArithmeticException数学运算异常

public class MyArithmeticExceptionTest {
public static void main(String[] args) {
int a = 10;
int b = 0;
System.out.println(a/b);
}

}

//ArrayIndexOutOfBoundsException :数组下标越界异常
public class MyArrayIndexOutOfBoundsException {
public static void main(String[] args) {
//定义的数组长特别大的时候也会出现数组下标越界异常
// int []a = new int[2*5*4546546*456465464];
// System.out.println(a[2]);

    //定义数组的长度为2 但是查找的是第三4个所以会出现数组下标越界异常
    int[] a = new int[2];
    System.out.println(a[3]);

    //定义数组的时候初始长度给一个负的值也会出现数组负下标异常异常

// int []a = new int[-5];

}

}

//类型装换异常
public class MyClassCastException {
public static void main(String[] args) {
Object object = new Object();
String str = (String) object;
}
}

//空指针转换异常
public class MyNullPointerException {
public static void main(String[] args) {
//当给一个字符串一个空字符串的形式的实时 不会出现空指针异常
//因为他不是空的
String str = ” “;
if(str.equals(” “)){
System.out.println(“我是空指针异常”);
}
//当给字符串一个null才会出现空指针异常
/*String str = null;
if(str.equals(null)){
System.out.println(“我是空指针异常”);
}*/
}
}

//数字格式异常
public class MyNumberFormatException {
public static void main(String[] args) {
//parseInt可以将字符串转换为一个十进制的数,当字符创不是数值内容的时候就会抛出数字格式异常
String str = “abc”;
System.out.println(Integer.parseInt(str));
}

}

猜你喜欢

转载自blog.csdn.net/weixin_42337796/article/details/81901034
今日推荐