throws与throw
生活随笔
收集整理的這篇文章主要介紹了
throws与throw
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.throws關鍵字
在定義一個方法時可以使用thows關鍵字聲明,使用throws聲明的方法表示此方法不處理異常,而交給方法的調用處進行處理,throws使用格式如下:
【throws使用格式】
public ?返回值類型 ?方法名稱(參數列表...)throws 異常類{}
范例:使用throws關鍵字
?
class Math{public int div(int i,int j)throws Exception{//方法可以不處理異常int temp=i/j;return temp;}}因為出發操作有可能出現異常,也有可能沒有異常,所以在上面的代碼的div()方法中使用了throws關鍵字,表示不管是否有異常,在調用此方法處都必須進行異常處理,代碼如下:
范例:處理異常
??
package test2;class Math {public int div(int i, int j) throws Exception {int temp = i / j;return temp;} }public class ThrowsDemo01 {public static void main(String[] args) {Math m = new Math();try {System.out.println("除法操作:" + m.div(60, 90));} catch (Exception e) {e.printStackTrace();}} }package test2;class Math {public int div(int i, int j) throws Exception {int temp = i / j;return temp;} }public class ThrowsDemo01 {public static void main(String[] args)throws Exception{Math m = new Math();try {System.out.println("除法操作:" + m.div(60, -50));} catch (Exception e) {e.printStackTrace();}} }
package test2;class Math {public int div(int i, int j) throws Exception {int temp = i / j;return temp;} }public class ThrowsDemo01 {public static void main(String[] args){Math m = new Math();try {throw new Exception("自己拋出一個異常"); // System.out.println("除法操作:" + m.div(60, -50));} catch (Exception e) {e.printStackTrace();}} }
結果:
java.lang.Exception: 自己拋出一個異常
at test2.ThrowsDemo01.main(ThrowsDemo01.java:14)
throw不會單獨使用,一般來講用戶都避免異常的產生,所以不會手工拋出一個異常的。
?
?
轉載于:https://www.cnblogs.com/bokun-wang/archive/2011/12/08/2280288.html
總結
以上是生活随笔為你收集整理的throws与throw的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在ASP.NET页面中动态添加控件
- 下一篇: 关于页面之间传参时有空格,中文及点击页面