python try catch finally_Java try catch finally异常处理(Exception)

1、Java Exceptions

执行Java代码时,可能会发生不同的错误异常:程序员编写的编码错误,由于输入错误引起的错误或其他不可预见的情况。

发生错误时,Java通常会停止并生成错误消息。 技术术语是:Java将引发异常(引发错误)。

2、Java try  catch

try语句允许定义要执行的错误代码块。

如果在try块中发生错误,则catch语句允许定义要执行的代码块。

try和catch关键字成对出现:

语法try {

//  要尝试的代码块

}

catch(Exception e) {

//  处理错误的代码块

}

考虑以下示例:

这将产生一个错误,因为myNumbers [10]不存在。输出将是这样的:public class Main{

public static void main(String[ ] args){

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[8]); // 不存在会报错!

}

}

如果发生错误,我们可以使用try catch来捕获错误并执行一些代码来处理该错误:

例如:public class Main{

public static void main(String[ ] args){

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[8]);

} catch (Exception e) {

System.out.println("输出异常信息等其它操作");

}

}

}

3、finally

finally语句可以在try catch之后执行代码,而不管是否在try代码中出现异常:

例如:public class Main{

public static void main(String[] args){

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[8]);

} catch (Exception e) {

System.out.println("输出异常信息等其它操作");

} finally {

System.out.println("执行资源释放等相关代码");

}

}

}

4、throw关键字

throw语句用于创建抛出自定义错误。

throw语句与异常类型一起使用。 Java中提供了许多异常类型:ArithmeticException,FileNotFoundException,ArrayIndexOutOfBoundsException,SecurityException等:

例如:public class Main{

static void checkValue(int x){

if (x < 0) {

throw new ArithmeticException("error is x < 0");

}

else {

System.out.println("x > 0");

}

}

public static void main(String[] args){

checkValue(15);

}

}public class DemoThrow{

public static void main(String[] args){

int a = DemoThrow.div(4,0);

System.out.println(a);

}

public static int div(int a,int b){

if(b==0)

throw new ArithmeticException("异常信息:除数不能为0");//抛出具体问题,编译时不检测

return a/b;

}

}

5、throws 关键字

throws关键字说明方法可能抛出的异常类型。

Java中有许多可用的异常类型:ArithmeticException,ClassNotFoundException,ArrayIndexOutOfBoundsException,SecurityException等。

例如:publicclassExample{

publicstaticvoidmain(String[] args){

try {

int result = divide(4,2);

System.out.println(result);

} catch (Exception e) {

e.printStackTrace();

}

}

publicstaticintdivide(int x,int y)throws Exception

{

int result = x/y;

return result;

}

}

throw和throws之间的区别:throwthrows

用于引发方法的异常用于指示方法可能抛出的异常类型

不能抛出多个异常可以声明多个异常

throw

throws

用于引发方法的异常

用于指示方法可能抛出的异常类型

不能抛出多个异常

可以声明多个异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值