java中的throw怎么使用

34次阅读
没有评论

共计 584 个字符,预计需要花费 2 分钟才能阅读完成。

在 Java 中,throw 关键字用于手动抛出一个异常。它通常用于方法中,当发生某种错误或条件不满足时,程序员可以使用 throw 关键字来抛出一个异常。
使用 throw 关键字的语法如下:

throw exception;

其中,exception 是要抛出的异常对象,可以是 Java 内置的异常类,也可以是自定义的异常类。
下面是一个使用 throw 关键字抛出异常的示例代码:

public class Example {public static void main(String[] args) {
try {int result = divide(10, 0);
System.out.println("结果:" + result);
}
catch (ArithmeticException e) {System.out.println("发生异常:" + e.getMessage());
}
}
public static int divide(int a, int b) {if (b == 0) {throw new ArithmeticException("除数不能为零");
}
return a / b;
}
}

在上面的代码中,divide 方法中使用 throw 关键字抛出一个 ArithmeticException 异常,如果参数 b 为 0,就会抛出该异常。在 main 方法中,我们使用 try-catch 语句捕获这个异常,并打印出异常信息。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-20发表,共计584字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)