1. 程式人生 > >安全程式設計(十四)- Java中throw和throws的區別

安全程式設計(十四)- Java中throw和throws的區別

1.粗淺來說

        throw是一個語句丟擲異常,throws是一個方法丟擲異常;

        throw不是和try-catch-finally配套使用就是和throws配套使用,而throws可以單獨使用。

2.例子

        2.1系統自動丟擲的異常

比如:

package cn.nuist.pers.October8;

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

此時系統會自動丟擲:

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at cn.nuist.pers.October8.ThrowThrows.main(ThrowThrows.java:7)

        2.2throw

如:

package cn.nuist.pers.October8;

public class ThrowThrows {
public static void main(String[] args) {
	
//	int a = 2,b = 0;
//	System.out.println(a/b);   系統自動丟擲異常
	
	String s = "abc";
	if(s.equals("abc")) {
		throw new NumberFormatException();
	}
	else {
		System.out.println(s);
	}
}
}

throw:

Exception in thread "main" java.lang.NumberFormatException
	at cn.nuist.pers.October8.ThrowThrows.main(ThrowThrows.java:11)

        2.3throws

如:

package cn.nuist.pers.October8;

public class ThrowThrows {
	
	public static void function() throws NumberFormatException {
		String s = "abc";
		System.out.println(Float.parseFloat(s));
	}
    public static void main(String[] args) {
	
	try {
		function();
	} catch (NumberFormatException e) {
		// TODO: handle exception
		System.out.println("噠噠噠!");
	}
}
}

throws:

噠噠噠!