61.RuntimeException运行时异常

跟風遠走 提交于 2020-02-03 00:59:47
  1. 算数ArithmeticException异常:试图除以0

     int b=0;
     System.out.println(1/b);  //error 
    
  2. 空指针NullPointerException异常

     String str = null;
     System.out.println(str.charAt(0));   //error 
    
  3. 类型转换ClassCastException异常

     Animal d = new Dog();
     Cat c = (Cat)d;  //error
    
  4. 数组越界ArrayIndexOutOfBoundsException异常

     int[] arr = new int[5];
     System.out.println(arr[5]);  //error
    
  5. 数字转型NumberFormatException异常

     String str2 = "1234abcf";
     System.out.println(Integer.parseInt(str2));  //error
    

异常的处理办法:

package yzy.exception;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class testRuntimeException {
	public static void main(String[] args) {
		//1. ArithmeticException异常:试图除以0
		int b=0;
		//System.out.println(1/b);  //error 
		
		//异常处理:
        if(b!=0) {
        	System.out.println(1/b);
        }
		
		
        //2. NullPointerException异常
        String str = null;
        //System.out.println(str.charAt(0));  //error
        
        //异常处理:  通常是增加非空判断
        if(str != null) {
        	System.out.println(str.charAt(0));
        }
        
        
        //3. ClassCastException异常
        Animal d = new Dog();
        //Cat c = (Cat)d;  //error
        
        //异常处理:  通常是增加非空判断
        if (d instanceof Cat) {
            Cat c = (Cat)d;
        }
        
        
        
        //4. ArrayIndexOutOfBoundsException异常
        int[] arr = new int[5];
        //System.out.println(arr[5]);  //error
        
        //异常处理:  增加关于边界的判断
        int a = 3;
        if (a < arr.length) {
            System.out.println(arr[a]);
        }
        
        
        
        //5. NumberFormatException异常
        String str2 = "1234abcf";
        //System.out.println(Integer.parseInt(str2));  //error
        
        //异常处理:  数字格式化异常的解决,可以引入正则表达式判断是否为数字
        Pattern p = Pattern.compile("^\\d+$");
        Matcher m = p.matcher(str2);
        if (m.matches()) { // 如果str2匹配代表数字的正则表达式,才会转换
            System.out.println(Integer.parseInt(str2));
        }
	}
}


class Animal{
    
}
class Dog extends Animal{
     
}
class Cat extends Animal{
     
}

注意事项

  1. 在方法抛出异常之后,运行时系统将转为寻找合适的异常处理器(exception handler)。潜在的异常处理器是异常发生时依次存留在调用栈中的方法的集合。当异常处理器所能处理的异常类型与方法抛出的异常类型相符时,即为合适的异常处理器。

  2. 运行时系统从发生异常的方法开始,依次回查调用栈中的方法,直至找到含有合适异常处理器的方法并执行。当运行时系统遍历调用栈而未找到合适的异常处理器,则运行时系统终止。同时,意味着Java程序的终止。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!