首页 > 编程知识 正文

声明异常的关键字,简述java中异常处理的机制

时间:2023-05-06 02:15:07 阅读:164794 作者:1166

Java异常处理的五个关键字

发布时间: 2020-08-23 03:37:55

来源:情景之家

阅读: 68

作者:彬彬菌

异常:可能是用户错误、程序错误或物理错误。

异常处理关键字: try、catch、finally、throw、throws

注意事项:

错误不是异常,而是脱离程序员控制的问题。

所有异常类都是从java.lang.Exception类继承的子类。

异常类有两个主要子类: IOException类和RuntimeException类。

Java有很多内置异常类。

异常的大致分类:

用户输入了不正确的数据。

要打开的文件不存在。

网络通信中连接中断或JVM内存溢出。

语法:

try{

//要侦听的代码块

}

catch (异常类型异常名称/e ) {

处理//try捕获到的错误的代码块

throw异常名称/e; //thorw表示抛出异常

throw new异常类型(“自定义”

}

法利{

//finally模块内的语句无论出现异常还是不出现异常都将被执行

}

限定符返回值方法名称() throws异常类型(throws仅用于声明异常,是否抛出由方法调用方决定

//代码块

}

代码示例: (try和catch和finally ) )。

公共类扩展测试{

publicstaticvoidmain (string [ ] args ) {

scanner input=new scanner (system.in );

拦截try{ //代码块

int a=input.nextInt (;

int b=input.nextInt (;

double sum=a/b;

system.out.println(sum;

}

catch(inputmismatchexceptione )

System.out.println ('只能输入数字);

}

缓存(arithmeticexceptione ) {

System.out.println ('分母不能为0 );

}

catch(exceptione ) { //Exception是所有异常的父类

System.out.println ('发生其他异常);

}

finally//无论有无异常,finally都一定会被执行

System.out.println (“程序结束”);

}

}

}

代码示例: (throw关键字)

import Java.util.inputmismatchexception;

import java.util.Scanner;

公共类扩展测试{

publicstaticvoidmain (string [ ] args ) {

scanner input=new scanner (system.in );

拦截try{ //代码块

int a=input.nextInt (;

int b=input.nextInt (;

double sum=a/b;

system.out.println(sum;

}

catch (inputmismatchexceptione (//catch ) )。

System.out.println ('只能输入数字);

throw e; 扔出catch捕捉到的异常

//thrownewinputmismatchexception (; 同上

}

缓存(arithmeticexceptione ) {

System.out.println ('分母不能为0 );

throw new ArithmeticException ('分母为0时抛出异常); 抛出ArithmeticException异常

}

catch(exceptione ) { //Exception是所有异常的父类

System.out.println ('发生其他异常);

}

finally//无论有无异常,finally都一定会被执行

System.out.println (“程序结束”);

}

}

}

代码示例: (throws )

公共类throws {

int a=1;

int b=0;

公共void out (throwsarithmeticexception ) /声明可能抛出的异常可以存在多个,用逗号分隔

拦截try{ //代码块

int sum=a/b;

system.out.println(sum;

}

缓存(arithmeticexceptione ) {

System.out.println ('分母不能为0 );

}

finally//无论有无异常,finally都一定会被执行

System.out.println (“程序结束”);

}

}

publicstaticvoidmain (string [ ] args ) {

Throws t=new Throws (;

t.out (; 调用//方法

throw new ArithmeticException ('分母为0时抛出异常); //调用的方法决定是否抛出异常

/*

*第二种慢速方法

*/

//arithmeticexceptiona=newarithmeticexception (“分母为0,抛出异常”);

//throw a;

}

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。