天天看點

Java千百問_04異常處理(003)_如何抛出異常

throws用來聲明某一個方法可能抛出的異常,這個異常可以是系統定義的,也可以是自己定義的。

調用throws修飾的方法,必須要對其做異常處理,或者将異常聲明抛出(使用throws)。

文法:

Java千百問_04異常處理(003)_如何抛出異常

import java.io.*;  

public class classname  

{  

public void deposit(double amount) throws remoteexception  

// method implementation  

}  

//remainder of class definition  

一個方法可以聲明它抛出多個異常,在這種情況下,異常都是在以逗号分割的形式聲明的。

Java千百問_04異常處理(003)_如何抛出異常

public void withdraw(double amount) throws remoteexception,  

insufficientfundsexception  

例子:

Java千百問_04異常處理(003)_如何抛出異常

public class exceptiontest{  

  public static void main(string args[]) throws ioexception, nullpointerexception{  

file = new fileinputstream(filename);  

x = (byte) file.read();  

這将産生以下結果:

at java.io.fileinputstream.open(native method)

異常被抛出,中斷執行,并列印了堆棧資訊。

使用throw關鍵字可以抛出一個異常對象。

另外,如果一個方法不處理異常,則該方法必須使用throws關鍵字聲明它。

Java千百問_04異常處理(003)_如何抛出異常

throw new remoteexception();  

Java千百問_04異常處理(003)_如何抛出異常

public void main(string[] args) throws exception  

throw new exception("異常");  

exception in thread "main" java.lang.exception: 異常

at com.test.test.main(test.java:37)

異常被抛出,并列印了堆棧資訊。

throws是用來聲明一個方法可能抛出的所有異常資訊。

throw則是指抛出的一個具體的異常對象。

原文位址:http://blog.csdn.net/ooppookid/article/details/51100373