49-抛出和捕获







抛出和捕获

异常处理机制

  • 抛出异常

  • 捕获异常

  • 异常处理五个关键字

    • trycatchfinallythrowthrows

示例

Application

public class Application {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {  //try 监控区域
            System.out.println(a/b);
        }catch (ArithmeticException e){  //catch 捕获异常
            System.out.println("被除数 b 不能为0");
        }finally {  //善后工作
            System.out.println("finally");
        }
    }
}

会获得输出

被除数 b 不能为0
finally

捕获异常之后,程序会继续运行,不会终止

finally 可以不需要。IO、资源一般需要 finally 关闭

catch () 中为想要捕获的异常类型。可以理解为类似 String 等类型,但是注意, String 不为异常类型,只是作为示例。

catch 可以层层捕获


Application

public class Application {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {  //try 监控区域
            System.out.println(a/b);
        }catch (Error e){  //catch 捕获异常
            System.out.println("Error");
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable e){
            System.out.println("Throwable");
        }finally {
            System.out.println("finally");
        }
    }
}

会获得输出

Exception
finally

因为 catch 只会执行一个,类似

if(){

}else if(){

}

只会执行一个 if

假设要捕获多个异常,异常范围要从小到大

抛出和捕获异常快捷键为 ctrl + alt + T

如果快捷键没有反应或者没有效果,可能是与其他软件的键位冲突,目前已知与 QQ 存在键位冲突

printStackTrace 为打印错误的栈信息

同样,可以抛出可能遇见的异常


Application

public class Application {
    public static void main(String[] args) {
        new Application().text(1,0);
    }
    public void text(int a,int b){
        if (b == 0){
            throw new ArithmeticException();  //手动抛出异常
        }
    }
}

会获得输出

Exception in thread "main" java.lang.ArithmeticException
    at Oop.Application.text(Application.java:16)
    at Oop.Application.main(Application.java:12)

这就是手动抛出异常,一般用在方法中

假设这个方法中,处理不了这个异常。方法抛出这个异常

public class Application {
    public static void main(String[] args) {
        try {
            new Application().text(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }
    public void text(int a,int b)throws ArithmeticException{
        if (b == 0){
            throw new ArithmeticException();  //手动抛出异常
        }
    }
}

算数异常属于运行时异常,正常情况下不需要手动抛出,程序自己会抛出

如果不使用 trycatch 程序会停止,如果使用 trycatch 捕获子厚,程序会继续运行


暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇