Java try-catch块

Java的try块用于封装可能会抛出异常的代码。它必须在方法内部使用。

如果在try块中的特定语句处发生异常,后续的代码块将不会执行。因此,建议不要在try块中放置不会抛出异常的代码。

Java的try块必须后跟catch块或finally块。

Java try-catch语法

try{    //可能引发异常的代码 }catch(Exception_class_Name ref){}

Java try-finally块的语法

try{    //可能引发异常的代码  }finally{}

Java catch块

Java的catch块用于通过在参数中声明异常类型来处理异常。声明的异常类型必须是父类异常(即Exception)或生成的异常类型。然而,良好的做法是声明生成的异常类型。

catch块必须在try块之后使用。可以在单个try块中使用多个catch块。

Java try-catch块的内部工作原理

JVM首先检查异常是否被处理。如果异常未被处理,JVM提供默认的异常处理程序,执行以下任务:

  • 打印异常描述。

  • 打印堆栈跟踪(异常发生的方法层次结构)。

  • 导致程序终止。

但是,如果应用程序程序员处理了异常,将保持应用程序的正常流程,即执行其余的代码。

没有异常处理的问题

让我们尝试理解如果我们不使用try-catch块会出现什么问题。

示例1

TryCatchExample1.java

public class TryCatchExample1 {        public static void main(String[] args) {                    int data=50/0; //可能会抛出异常                     System.out.println("rest of the code");                }        }
 

输出:

Exception in thread "main" java.lang.ArithmeticException: / by zero
 

如上例所示,未执行后续的代码(在这种情况下,未打印后续的代码语句)。

如果异常没有被处理,异常下面的所有代码都不会被执行。

通过异常处理的解决方案

让我们通过Java的try-catch块来解决上述问题。

示例2

TryCatchExample2.java

public class TryCatchExample2 {        public static void main(String[] args) {          try          {          int data=50/0; //可能会抛出异常          }              //处理异常         catch(ArithmeticException e)          {              System.out.println(e);          }          System.out.println("rest of the code");      }        }
 

输出:

java.lang.ArithmeticException: / by zerorest of the code
 

如上例所示,执行了后续的代码,即打印了后续的代码语句。

示例3

在这个示例中,我们还将不会抛出异常的代码放在了try块中

TryCatchExample3.java

public class TryCatchExample3 {        public static void main(String[] args) {          try          {          int data=50/0; //可能会抛出异常                            // 如果发生异常,其余语句将不会执行        System.out.println("rest of the code");          }               // 处理异常         catch(ArithmeticException e)          {              System.out.println(e);          }                }        }
 

输出:

java.lang.ArithmeticException: / by zero
 

在上述示例中,我们可以看到如果在try块中发生异常,后续的代码块将不会执行。

示例4

在这个示例中,我们使用父类异常来处理异常。

TryCatchExample4.java

public class TryCatchExample4 {        public static void main(String[] args) {          try          {          int data=50/0; //可能会抛出异常        }              // 使用异常类处理异常        catch(Exception e)          {              System.out.println(e);          }          System.out.println("rest of the code");      }        }
 

输出:

java.lang.ArithmeticException: / by zerorest of the code
 

示例5

让我们看一个在异常上打印自定义消息的示例。

TryCatchExample5.java

public class TryCatchExample5 {        public static void main(String[] args) {          try          {          int data=50/0; //可能会抛出异常         }               //处理异常          catch(Exception e)          {                    // 显示自定义消息            System.out.println("Can't divided by zero");          }      }        }
 

输出:

Can't divided by zero
 

示例6

让我们看一个在catch块中解决异常的示例。

TryCatchExample6.java

public class TryCatchExample6 {        public static void main(String[] args) {          int i=50;          int j=0;          int data;          try          {          data=i/j; //可能会抛出异常        }              // 处理异常          catch(Exception e)          {               // 解决 catch 块中的异常            System.out.println(i/(j+2));          }      }  }
 

输出:

25
 

示例7

在这个示例中,除了try块,我们还将异常代码放在了catch块中

TryCatchExample7.java

public class TryCatchExample7 {        public static void main(String[] args) {                    try          {          int data1=50/0; //可能会抛出异常           }               //处理异常          catch(Exception e)          {              // 在 catch 块中生成异常        int data2=50/0; //可能会抛出异常        }      System.out.println("rest of the code");      }  }
 

输出:

Exception in thread "main" java.lang.ArithmeticException: / by zero
 

在这里,我们可以看到catch块中没有包含异常代码。因此,在try块中包含异常代码,并且仅在catch块中处理异常。

示例8

在这个示例中,我们使用不同类型的异常类(ArrayIndexOutOfBoundsException)处理生成的异常(Arithmetic Exception)。

TryCatchExample8.java

public class TryCatchExample8 {        public static void main(String[] args) {          try          {          int data=50/0; //可能会抛出异常             }              // 尝试使用 ArrayIndexOutOfBoundsException 处理 ArithmeticException        catch(ArrayIndexOutOfBoundsException e)          {              System.out.println(e);          }          System.out.println("rest of the code");      }        }
 

输出:

 
Exception in thread "main" java.lang.ArithmeticException: / by zero

示例9

让我们看一个处理另一个未检查异常的示例。

TryCatchExample9.java

public class TryCatchExample9 {        public static void main(String[] args) {          try          {          int arr[]= {1,3,5,7};          System.out.println(arr[10]); //可能会抛出异常        }              // 处理数组异常          catch(ArrayIndexOutOfBoundsException e)          {              System.out.println(e);          }          System.out.println("rest of the code");      }        }
 

输出:

java.lang.ArrayIndexOutOfBoundsException: 10rest of the code

示例10

让我们看一个处理已检查异常的示例。

TryCatchExample10.java

import java.io.FileNotFoundException;  import java.io.PrintWriter;    public class TryCatchExample10 {        public static void main(String[] args) {                              PrintWriter pw;          try {              pw = new PrintWriter("jtp.txt"); //可能会抛出异常            pw.println("saved");          }  // 提供已检查的异常处理程序  catch (FileNotFoundException e) {                            System.out.println(e);          }             System.out.println("File saved successfully");      }  }
 

输出:

File saved successfully

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

技术宅chat

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值