亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

關于throw?

本節中

throw new DrunkException();拋出異常類,拋出的是類

throw newExc;拋出對象。

能拋出對象?

拋出對象時格式不一樣,不用寫new ?

throw 能拋出哪些?

正在回答

5 回答

拋出異常的方法有2種:

1)在方法體內部使用throw語句拋出異常對象,格式是:throw +有異常類所產生的對象

2)就是老師講的:[修飾符] 返回值類型 ?方法名(參數列表)throws ?+異常列表。

這個例子中newExc是由RuntimeException創建的對象,所以用throw newExc;

0 回復 有任何疑惑可以回復我~

public class test_1 {

?? ?public static void main(String[] args) {
?? ??? ?test_1 result = new test_1();
?? ??? ?result.deal2();
?? ?}
?? ?public class DIYException1 extends Exception {
?? ??? ?public DIYException1() {
?? ??? ?}
?? ?}
?? ?public class DIYException2 extends Exception {
?? ??? ?public DIYException2() {
?? ??? ?}
?? ?}
?? ?//自定義兩種異常
?? ?public void test() throws DIYException1 {
?? ??? ?throw new DIYException1();
?? ?}
?? ?//通過test(),拋出異常1
?? ?public void deal1() throws DIYException2 {
?? ??? ?try {
?? ??? ??? ?test();
?? ??? ?} catch (DIYException1 e) {
?? ??? ??? ?System.out.println("error1");
?? ??? ??? ?throw new DIYException2();
?? ??? ?}?? ?
?? ?}
?? ?//檢測到異常1拋出后,拋出異常2,并輸出error1
?? ?public void deal2() {
?? ??? ?try {
?? ??? ??? ?deal1();
?? ??? ?} catch (DIYException2 e) {
?? ??? ??? ?System.out.println("error2");
?? ??? ?}
?? ?}
?? ?//檢測到異常2后,輸出error2
}

0 回復 有任何疑惑可以回復我~

throw關鍵字通常用在方法體中,并且拋出一個異常對象。程序在執行到throw語句時立即停止,它后面的語句都不執行。通過throw拋出異常后,如果想在上一級代碼中來捕獲并處理異常,則需要在拋出異常的方法中使用throws關鍵字在方法聲明中指明要跑出的異常;如果要捕捉throw拋出的異常,則必須使用try—catch語句。舉例如下:
package imooc;

class MyException extends Exception { // 創建自定義異常類
?? ?String message; // 定義String類型變量

?? ?public MyException(String ErrorMessagr) { // 父類方法
?? ??? ?message = ErrorMessagr;
?? ?}

?? ?public String getMessage() { // 覆蓋getMessage()方法
?? ??? ?return message;
?? ?}
}

public class ThrowTest { // 創建類
?? ?static int quotient(int x, int y) throws MyException {// 定義方法拋出異常
?? ??? ?if (y < 0) { // 判斷參數是否小于0
?? ??? ??? ?throw new MyException("除數不能是負數");// 異常信息
?? ??? ?}
?? ??? ?return x / y;// 返回值
?? ?}

?? ?public static void main(String args[]) { // 主方法
?? ??? ?try { // try語句包含可能發生異常的語句
?? ??? ??? ?int result = quotient(3, -1);// 調用方法quotient()
?? ??? ?} catch (MyException e) { // 處理自定義異常
?? ??? ??? ?System.out.println(e.getMessage()); // 輸出異常信

?? ??? ?} catch (ArithmeticException e) {
?? ??? ??? ?// 處理ArithmeticException異常
?? ??? ??? ?System.out.println("除數不能為0");// 輸出提示信息
?? ??? ?} catch (Exception e) { // 處理其他異常
?? ??? ??? ?System.out.println("程序發生了其他的異常");
?? ??? ??? ?// 輸出提示信息
?? ??? ?}
?? ?}
}

2 回復 有任何疑惑可以回復我~

拋出的都是異常類對象,

0 回復 有任何疑惑可以回復我~

new DrunkException();這句,有new,這句話就是實例化過程,所以拋出的是對象

總之,throw拋出的是異常對象。不可能拋出一個類,類是抽象概念嘛~

0 回復 有任何疑惑可以回復我~
#1

wshyzx 提問者

能拋出方法?能拋出變量?能拋出字符串?
2016-07-18 回復 有任何疑惑可以回復我~
#2

慕粉3657542 回復 wshyzx 提問者

這就不知道了,只知道能拋出異常類的實例對象
2016-07-18 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消
Java入門第三季
  • 參與學習       409767    人
  • 解答問題       4543    個

Java中你必須懂得常用技能,不容錯過的精彩,快來加入吧

進入課程

關于throw?

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號