java中的异常

本文介绍了Java中异常处理的基本概念,并通过实例演示了如何捕获和处理ArrayIndexOutOfBoundsException和ArithmeticException等常见异常。

java中的异常

TestExceptions.java

//异常
public class TestExceptions {
	public static void main(String[] args) {
		int[] arr = {1, 2, 3};
		//编译通过,运行时出现异常
		System.out.println(arr[4]);
	}
}
F:\java>javac TestExceptions.java

F:\java>java TestExceptions
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
        at TestExceptions.main(TestExceptions.java:6)

F:\java>

 出现了异常,异常为:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
        at TestExceptions.main(TestExceptions.java:6)

在main这个线程中的TestExceptions.java的第6行出现了异常,异常的原因为数字4。

ArrayIndexOutOfBoundsException

网络数组下标越界异常;数组索引越界异常;数组越界

 

//异常
public class TestExceptions {
	public static void main(String[] args) {
		
		System.out.println(2/0);
	}
}

 

F:\java>javac TestExceptions.java

F:\java>java TestExceptions
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at TestExceptions.main(TestExceptions.java:5)

F:\java>

 出现了异常:java.lang.ArithmeticException: / by zero ;除以0异常。

ArithmeticException

算术异常

 

使用try...catch捕获异常

//异常
public class TestExceptions {
	public static void main(String[] args) {
		try {
			System.out.println(2/0);
		} catch (ArithmeticException e) {
			System.out.println("系统正在维护,请与管理员联系");
			e.printStackTrace();//打印堆栈信息
		}
	}
}

 

F:\java>java TestExceptions
系统正在维护,请与管理员联系
java.lang.ArithmeticException: / by zero
        at TestExceptions.main(TestExceptions.java:5)

F:\java>

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值