JAVA异常

开发工具与关键技术: MyEclipse 10 / JAVA基础
撰写时间:2020年6月16日

JAVA异常

Java的异常处理机制可以让程序具有极好的容错性,让程序更加健壮。当程序运行出现意外情形时,系统会自动生成一个 Exception对象来通知程序,从而实现将“业务功 能实现代码”和“错误处理代码”分离,提供更好的可读性。Java异常处理机制为:抛出异常、捕捉异常和处理异常。
下面是一个使用try…catch捕获异常的案例代码:

package com.gx.demo;
public class ExceptionDemo {
	public static void main(String[] args) {
		String[] strs = {"10","0"};//算术异常(除零)
		fangfa (strs);
	}
	public static void fangfa (String[] strs){
		try {
			int a = Integer.parseInt(strs[0]);
			int b = Integer.parseInt(strs[1]);					 
			int c = a / b;
			System.out.println("结果是:" + c);
								
		} catch (ArrayIndexOutOfBoundsException aae) {
			// TODO: handle exception
			System.out.println("数组索引越界:输入的参数个数不够");
			aae.printStackTrace();					
			
		} catch (NumberFormatException ne) {
			// TODO: handle exception
			System.out.println("数字格式异常,程序只能接受整数参数");
			ne.printStackTrace();
			
		} catch (ArithmeticException ae) {
			// TODO: handle exception
			System.out.println("算数异常");
			ae.printStackTrace();
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("其他异常");
			e.printStackTrace();
		}		
	}
}
String[] strs = {"10","0"};

如果值里有零,那么就会报算术异常“ArithmeticException”。
下面是结果图:
JAVA异常_第1张图片

String[] strs = {"10.5","0"};

如果值不是数字整数时,那么就会报数字格式异常 “NumberFormatException”。
下面是结果图:
JAVA异常_第2张图片

int a = Integer.parseInt(strs[1]);
int b = Integer.parseInt(strs[2]);

如果获取数组的索引不符合,那么就会报 数组索引越界 “ArrayIndexOutOfBoundsException”。
下面是结果图:
JAVA异常_第3张图片
在使用try…catch捕获处理异常时需要注意:1、不要过度使用异常,不能使用异常处理机制来代替正常的流程控制语句;2、异常捕获时,一定要先捕获小异常,再捕获大异常。否则小异常将无法被捕获;3、 避免出现庞大的try块;4、避免使用catch(Exception e){} ;5、不要忽略异常。

你可能感兴趣的:(Java基础,java)