Throwable 是异常的父类。在java.lang包中。
Error : Throwable的子类,表示错误。这种问题是程序员无法解决的问题。所以一般也不会过多的研究这个类和其子类。在java.lang包中
Exception:所有异常的父类。出现这些情况都是程序员能够解决的。在java.lang包中
RuntimeException:Exception 的子类。表示运行时异常,又称非检查时异常。这种异常只有在程序运行过程中才会出现。在java.lang包中
常见异常类 运行时异常RuntimeException
【1】Exception in thread “main” java.lang.NullPointerException 空指针异常
原因: 获得到对象本身是一个null 我们继续使用空对象调用其他方法 就会导致空指针异常
public static void main(String[] args) {
String str1 = null;
String str2 = "张三";
System.out.println(str1.length() + ", " + str2.length());
}
【2】Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 数组下标越界
原因: 数组下标超过了界限
public static void main(String[] args) {
int[] nums = new int[3];
System.out.println(nums[3]);
}
【3】Exception in thread “main” java.lang.ArithmeticException: / by zero 算数异常
原因: 分母为0报出异常
int i = 5/0;
【4】Exception in thread “main” java.lang.ClassCastException 类型转换错误
原因: 把某一个类强制转换成其他类 这个时候就会出现类型转换错误
Car car = new Car(); Benz benz = (Benz)car;
【5】Exception in thread “main” java.lang.NumberFormatException 数字格式错误
原因 一般在字符串和数字类型进行转换的时候 格式错误导致的异常
String str = "你好"; int i = Integer.parseInt(str);
检查时异常
InterruptedException /IOException
处理机制 try {} catch{} finally{}捕获异常 整个异常的处理都是我们自己完成的
public static int aa()
{
try {
int a = 10/0;
return 1;
} catch (Exception e) { //Exception 可换成具体的子类如 ArithmeticException | NullPointerException
//System.out.println(e.getMessage());
// e.getStackTrace();
return 10;
} finally {
return 100; //必定执行
}
}
public static void main(String[] args) {
System.out.println(aa());
}
//100
throw
可以在代码内部定义抛出异常类型
public static int aa()
{
try {
int a = 10/0;
return 1;
} catch (Exception e) {
throw new ArithmeticException();
// return 10;
} finally {
// return 100; //必定执行
}
}
public static void main(String[] args) {
System.out.println(aa());
}
//Exception in thread "main" java.lang.ArithmeticException
//...
throws: 抛出的异常只可以在方法后书写 定义抛出异常类型
访问权限修饰符 返回值类型 方法名(参数) throws 异常类型,异常类型{ }
public static int aa(int j,int i) throws Exception
{
return i/j;
}
public static void main(String[] args) {
System.out.println(aa(10,0)); //代码编译报错
}
//解决方法
public static void main(String[] args) throws Exception {
System.out.println(aa(10,0)); //错误解决
}
public static void main(String[] args) {
try {
System.out.println(aa(10,0));
} catch (Exception e) {
e.printStackTrace();
}
}
自定义异常类
//继承RuntimeException 或Exception
public class MenuIndexOutOfBoundsExecption extends RuntimeException{
public MenuIndexOutOfBoundsExecption(){
super();
}
public MenuIndexOutOfBoundsExecption(String s){
super(s);
}
}
throw new MenuIndexOutOfBoundsExecption("菜单输入错误");



