java中的异常

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

算术异常

扫描二维码关注公众号,回复: 361541 查看本文章

使用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>

 

猜你喜欢

转载自mfcfine.iteye.com/blog/2382477