Java学习之RuntimeException类举例分析
在Oracle官网上列出了RuntimeException类的直接子类
现分析其中的一些常见子类
1.ArithmeticException
发生情况:当发生异常算术条件时抛出。例如,整数“除以零”抛出该类的实例。
举例分析:
public class TestArithmeticException {
public static void main(String[] args) {
int a = 100;
int b = 0;
int c;
try{
c = a / b;
}
catch (ArithmeticException ae)
{
System.out.println(ae);
}
}
}
//程序输出:
//java.lang.ArithmeticException: / by zero
2.NullPointerException
发生情况:当应用程序试图在需要对象的情况下使用null
时抛出。这些包括:
- 调用
null
对象的实例方法。 - 访问或修改
null
对象的字段。 - 将
null
的长度视为数组。 - 访问或修改
null
插槽,就像它是数组一样。 Throwable
的值一样抛出null
值。
应用程序应抛出此类实例,以指示null
对象的其他非法用途。
举例分析:
public class TestNULLPointerException {
private static int[] x;
public static void main(String[] args){
try{
System.out.println(x[0]);
}
catch (NullPointerException nu){
System.out.println(nu);
}
}
}
//程序输出:
//java.lang.NullPointerException: Cannot load from int array because "TestNULLPointerException.x" is null
3.ClassCastException
发生情况:抛出以指示代码已尝试将对象转换为它不是实例的子类。
举例分析:
public class TestClassCastException {
public static void main(String[] args) {
Integer x = new Integer(0);
String y;
try {
System.out.println((String)x);
}
catch (ClassCastException ca){
System.out.println(ca);
}
}
}
//程序输出:
//Inconvertible types; cannot cast 'java.lang.Integer' to 'java.lang.String'
4.ArrayStoreException
发生情况:抛出以指示已尝试将错误类型的对象存储到对象数组中。
举例分析:
public class TestArrayStoreException {
public static void main(String[] args) {
String[] x = new String[3];
try {
x[0] = new Integer(0);
}
catch (ArrayStoreException arrayStoreException){
System.out.println(arrayStoreException);
}
}
}
//程序输出:
//java: 不兼容的类型: java.lang.Integer无法转换为java.lang.String
5.NegativeArraySizeException
发生情况:如果应用程序试图创建负大小的数组,则抛出。
举例分析:
public class TestArrayStoreException {
public static void main(String[] args) {
try {
String[] x = new String[-1];
}
catch (ArrayStoreException arrayStoreException){
System.out.println(arrayStoreException);
}
}
}
//程序输出:
//Exception in thread "main" java.lang.NegativeArraySizeException: -1
//at TestArrayStoreException.main(TestArrayStoreException.java:5)