当程式发生错误而无法处理的时候,会丢出对应的例外物件,除此之外,在某些时刻,您可能会想要自行丢出例外,例如在例外处理结束后,再将例外丢出,让下一层例外处理区块来捕捉,若想要自行丢出例外,您可以使用"throw"关键字,并生成指定的例外物件,例如:
throw new ArithmeticException(); 举个例子来说明,在Java的除法中,允许除数为浮点数0.0,所得到的是Infinity,即无穷数,如果您想要自行检验除零错误,可以自行丢出例外,最接近这个条件的是ArithmeticException,当除数为整数且为0时,就会引发这个例外,您可以如下丢出例外:
public class UseThrow { 执行结果:
每个例外都必须有一个"catch"区块来捕捉,在巢状的try...catch时,必须注意该例外是由何者引发并由何者捕捉,例如:
public class UseThrow {
执行结果:
在这个程式中,ArrayIndexOutOfBoundsException由内层try-catch丢出并捕捉,由于内层已经捕捉了例外,所以外层的try-catch中之ArrayIndexOutOfBoundsException并不会捕捉到内层所丢出的例外,但如果内层的try-catch并没有捕捉到这个例外,则外层try-catch就有机会捕捉这个例外,例如:
public class UseThrow { 执行结果:
程式中会订定许多方法(Method),这些方法中可能会因某些错误而引发例外,但您不希望直接在这个方法中处理这些例外,而希望呼叫这个它的方法来统一处理,这时候您可以使用"throws"关键字来宣告这个方法将会丢出例外,例如:
private void arrayMethod(int[] arr) throws ArrayIndexOutOfBoundsException, ArithmeticException { // 实作 } 注意如果会丢出多种可能的例外时,中间使用逗点分隔;当有方法上使用"throws"宣告例外时,意味着呼叫该方法的呼叫者必须处理这些例外,而被呼叫方法可以保持程式逻辑的简洁,下面这个范例是"throws"的一个简单示范:
public class UseThrows { 执行结果:
简单的说,您要不就在方法中直接处理例外,要不就在方法上宣告该方法会丢回例外,由呼叫它的呼叫者来处理例外,另一方面,在方法上使用 "throws"宣告可丢出的例外,也表示了您只能丢出所宣告类型的例外,其它的例外您必须在方法中处理完,或是重新包装为所宣告的例外再丢出。 如果使用继承时,在父类别的某个方法上宣告了throws某些例外,而在子类别中重新定义该方法时,您可以:
但是您不可以:
| <script type="text/javascript">
</script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script> name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-9750319131714390&dt=1197174918310&lmt=1181153048&format=160x600_as&output=html&correlator=1197174918216&url=http%3A%2F%2Fcaterpillar.onlyfun.net%2FGossipCN%2FJavaGossip-V1%2FThrowThrows.htm&ad_type=text_image&ref=http%3A%2F%2Fwww.baidu.com%2Fbaidu%3Ftn%3Dmyie2dg%26ie%3Dutf-8%26word%3Dthrow%2520throws&cc=280&ga_vid=659648747.1197174918&ga_sid=1197174918&ga_hid=1015853596&flash=9&u_h=768&u_w=1024&u_ah=738&u_aw=1024&u_cd=32&u_tz=480&u_java=true" frameborder="0" width="160" scrolling="no" height="600" allowtransparency="allowtransparency"> <script type="text/javascript"> </script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script> name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-9750319131714390&dt=1197174918466&lmt=1181153048&prev_fmts=160x600_as&format=160x600_as&output=html&correlator=1197174918419&url=http%3A%2F%2Fcaterpillar.onlyfun.net%2FGossipCN%2FJavaGossip-V1%2FThrowThrows.htm&ad_type=text_image&ref=http%3A%2F%2Fwww.baidu.com%2Fbaidu%3Ftn%3Dmyie2dg%26ie%3Dutf-8%26word%3Dthrow%2520throws&cc=280&ga_vid=659648747.1197174918&ga_sid=1197174918&ga_hid=1015853596&flash=9&u_h=768&u_w=1024&u_ah=738&u_aw=1024&u_cd=32&u_tz=480&u_java=true" frameborder="0" width="160" scrolling="no" height="600" allowtransparency="allowtransparency"> |
Java Gossip: throw、throws
最新推荐文章于 2023-04-11 21:04:13 发布