Java中的异常及处理

Java中的异常及处理

1.Java中出现问题使用ThrowAble表示

其中ThrowAble又分两类,分别是Error(错误),和Exception(异常)

Error(错误):不是程序员可以通过代码解决的问题,例如内存溢出。
Exception(异常):是由于编写程序时,没有考虑周全,从而发生的问题。

下面列举编写过程中几个常见的异常:

public class ExceptionShow{
	
	public static void main(String[] args){
		//1)算数异常之0不能作为除数 ———— java.lang.ArithmeticException: / by zero
		try{
			int a = 1/0;
		}catch(ArithmeticException e) {
			//e.printStackTrace();//该方法用于显示异常信息
			System.out.println("0不能作为除数");
		}
		
		//2)空指针异常 ———— NullPointException
		try{
			String name = null;
			System.out.println(name.toString());
		}catch(NullPointException e) {
			System.out.println("空指针异常");
		}

		//3)越界三兄弟
		//  1.数组下标越界 ———— ArrayIndexOutOfBoundsException
		try{
			int[] intArr = new int[] {};
			System.out.println(intArr[0]);
		}catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("数组下标越界");
		}
		//  2.字符串下标越界 ———— StringIndexOutOfBoundsException
		try{
			String name = "Hello World!";
			System.out.println(name.substring(-1));
		}catch(StringIndexOutOfBoundsException e) {
			System.out.println("字符串下标越界");
		}
		//  3.集合下标越界 ———— IndexOutOfBoundsException
		try{
			ArrayList<String> strList = new ArrayList<String>();
			System.out.println(strList.get(0));
		}catch(IndexOutOfBoundsException e) {
			System.out.println("集合下标越界");
		}

		//4)数字格式化异常 ———— NumberFormatException
		try{
			Integer num = Integer.parseInt(null);
			System.out.println(num);
		}catch(NumberFormatException e) {
			System.out.println("数字格式化异常");
		}
		
		//5)输入异常 ———— InputMismatchException
		try{
			Scanner s = new Scanner(System.in);
			int num = s.nextInt();
		}catch(InputMismatchException e) {
			System.out.println("输入异常");
		}
		
		//由于所有的异常都直接或者间接的继承于Exception类,所以Exception可以处理所有的异常
		//多重处理时,Exception通常写在最后
		try{
			//可能出现异常的代码
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}

备注:try{}catch{}的作用:(防止程序崩溃)
如果存在没有被处理的异常,那么发生异常时程序直接退出(程序崩溃)。
所以这时候需要用try,catch进行处理,其中try里面放可能会出现异常的代码,catch里面用于抛出异常

关于finally代码块在抛异常中的使用

public class Test{
	public static void main(String[] args){
		try{
			//可能出现异常的代码
		}catch(Exception e) {
			e.printStackTrace();
		}finally{
			//出现或者不出现异常都需要执行的代码
		}
	}
}

Java中异常分为两种:
1.编译时异常
编写完代码以后立即出现异常,异常不解决代码不能通过编译。
备注:编译时异常一般直接或者间接继承Exception
2.运行时异常
编写完代码之后不会出现异常提示,代码可以正常编译,只是在运行时可能会出现异常信息。
备注:运行时异常一般直接或者间接继承RuntimeException

最后关于throws抛出异常,就不多讲了,分为两种:
1.方法抛出异常(表示此方法运行时会出现异常)
2.代码块中抛出异常(手动制造异常)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值