JAVA异常之异常处理

一、常见的异常

public class ExceptionDemo01 {

	public static void main(String[] args) {
		
		//1.java.lang.NullPointerException空指针异常
		/*String str = null;
		System.out.println(str.length());*/
		
		//2.java.lang.ArrayIndexOutOfBoundsException数组索引越界异常
		/*int[] arr  =new int[10];
		arr[10]=10;*/
		
		//3.java.lang.IndexOutOfBoundsException索引越界异常
		/*List list = new ArrayList<>();
		list.get(0);*/
		
		
		//4.java.lang.ArithmeticException算术异常
		/*System.out.println(10/0);*/
		
		//5.java.lang.NumberFormatException数据格式化异常
		/*String str = "abv";
		Integer.parseInt(str);*/
		
		//6.java.util.InputMismatchException输入不匹配异常
		/*Scanner scan = new Scanner(System.in);
		int a = scan.nextInt();*/
		
		//7.java.lang.ClassCastException类转化异常
		
	}

}
二、解决异常

① 抛给上一级(并未解决异常)

② try catch

public class ExceptionDemo02 {

	public static void main(String[] args) {
		String str = null;
		int [] arr = new int[10];
		try{
			arr[10]=10;
		}catch(NullPointerException e){
			e.printStackTrace();
			System.out.println("发生了空指针异常");
		}catch (ArrayIndexOutOfBoundsException e) {
			e.printStackTrace();
			System.out.println("发生了数组越界异常");
		}catch (Exception e) {
			//总会执行的语句
		}
		System.out.println("************");
	}

}
三、自定义异常

public class MyException extends Exception{
	public MyException(String msg){
		super(msg);
	}
}

public class ExceptionDemo03 {

	public static void main(String[] args) {
		int age = 150;
		if(age<0 || age>100){
			try {
				throw new MyException(String.valueOf(age));
			} catch (MyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值