Java基础-throw和throws

虽然了解一些有关 Java 的异常处理,但是发现自己对 throw 和 throws 二者还不是很清楚,所以想深入的理解理解。

抛出异常的三种方式

系统自动抛出异常、throw 和 throws三种方式。

1、系统自动抛出异常

public class ThrowTest {
	
	public static void main(String[] args) {
		int a = 0;
		int b = 1;
		System.out.println(b / a);
	}

}

运行该程序后系统会自动抛出 ArithmeticException 算术异常。

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at com.sywf.study.ThrowTest.main(ThrowTest.java:8)

2、throw
throw 指的是语句抛出异常,后面跟的是对象,如:throw new Exception,一般用于主动抛出某种特定的异常,如:

public class ThrowTest {
	
	public static void main(String[] args) {
		String string = "abc";
		if ("abc".equals(string)) {
			throw new NumberFormatException();
		} else {
			System.out.println(string);
		}
	}

}

运行后抛出指定的 NumberFormatException 异常。

Exception in thread "main" java.lang.NumberFormatException
	at com.sywf.study.ThrowTest.main(ThrowTest.java:8)

3、throws
throws 用于方法名后,声明方法可能抛出的异常,然后交给调用其方法的程序处理,如:

public class ThrowTest {

	public static void test() throws ArithmeticException {
		int a = 0;
		int b = 1;
		System.out.println(b / a);
	}

	public static void main(String[] args) {
		try {
			test();
		} catch (ArithmeticException e) {
			// TODO: handle exception
			System.out.println("test() -- 算术异常!");
		}
	}

}

程序执行结果:

test() -- 算术异常!

throw 与 throws 比较

1、throw 出现在方法体内部,而 throws 出现方法名后。
2、throw 表示抛出了异常,执行 throw 则一定抛出了某种特定异常,而 throws 表示方法执行可能会抛出异常,但方法执行并不一定发生异常。

posted @ 2018-12-27 11:08  扇影无风  阅读(2543)  评论(0编辑  收藏  举报