Java异常处理编程:捕获和重写

原创 谁借莪1个温暖的怀抱¢ 2024-10-17 19:18 92阅读 0赞

在Java中,异常处理是一种机制,用于在程序运行过程中遇到错误时进行处理。主要的异常处理流程包括抛出异常、捕获异常以及重写异常。

  1. 抛出异常:
    当代码执行过程中出现问题时,可以使用throw关键字抛出一个异常对象。例如:
  1. public class Example {
  2. public void divide(int a, int b) {
  3. if (b == 0) {
  4. throw new IllegalArgumentException("Divisor cannot be zero");
  5. }
  6. //... further code
  7. }
  8. public static void main(String[] args) {
  9. Example example = new Example();
  10. try {
  11. example.divide(10, 0);
  12. } catch (IllegalArgumentException e) {
  13. System.out.println("Caught exception: " + e.getMessage());
  14. }
  15. }
  16. }
  1. 捕获异常:
    当一个方法或代码块可能抛出特定异常时,可以在这些地方使用try-catch结构来捕获异常。例如:
  1. public class Example {
  2. public void divide(int a, int b) throws IllegalArgumentException {
  3. if (b == 0) {
  4. throw new IllegalArgumentException("Divisor cannot be zero");
  5. }
  6. //... further code
  7. }
  8. public static void main(String[] args) {
  9. Example example = new Example();
  10. try {
  11. example.divide(10, 0);
  12. } catch (IllegalArgumentException e) {
  13. System.out.println("Caught exception: " + e.getMessage());
  14. }
  15. }
  16. }
  1. 重写异常:
    如果你想要处理特定的异常,但不想完全捕获它,而是希望以某种方式改变或重新抛出这个异常。你可以使用throws关键字在方法声明中指定可能抛出的异常,并在该方法内部重写这些异常。

例如:

  1. public class Example {
  2. public void divide(int a, int b) throws IllegalArgumentException, ArithmeticException {
  3. if (b == 0) {
  4. throw new IllegalArgumentException("Divisor cannot be zero");
  5. }
  6. // ... further code
  7. try {
  8. // ... potentially risky arithmetic operation
  9. } catch (ArithmeticException e) {
  10. System.out.println("Caught arithmetic exception: " + e.getMessage());
  11. throw e; // rethrow the caught exception
  12. }
  13. }
  14. public static void main(String[] args) {
  15. Example example = new Example();
  16. try {
  17. example.divide(10, 0);
  18. } catch (IllegalArgumentException | ArithmeticException e) {
  19. System.out.println("Caught or rethrown exception: " + e.getMessage());
  20. }
  21. }
  22. }

在这个例子中,我们重写了divide方法可能抛出的IllegalArgumentExceptionArithmeticException。如果捕获到这些异常,我们会根据需要打印异常信息,并重新抛出异常,以保持程序的控制流。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,92人围观)

还没有评论,来说两句吧...

相关阅读