Java 异常 try...catch



  • Java异常

    在执行Java代码时,可能会发生不同的错误:程序员编写的编码错误,由于输入错误引起的错误或其他不可预见的事情。发生错误时,Java通常会停止并生成错误消息。技术术语是:Java将引发异常(引发错误)。
  • Java try...Catch

    try语句允许您定义要执行的错误代码块。如果try块中发生错误,则catch语句允许您定义要执行的代码块。trycatch关键字成对出现的:
    语法:
    try {
      //  Block of code to try
    }
    catch(Exception e) {
      //  Block of code to handle errors
    }
    
    考虑以下示例:
    这将产生一个错误,因为myNumbers[10]不存在。
    public class MyClass {
      public static void main(String[ ] args) {
        int[] myNumbers = {1, 2, 3};
        System.out.println(myNumbers[10]); // error!
      }
    }
    
    输出将是这样的:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
            at MyClass.main(MyClass.java:4)
    
    如果发生错误,我们可以用try...catch来捕获错误并执行一些代码来处理它:
    public class MyClass {
      public static void main(String[ ] args) {
        try {
          int[] myNumbers = {1, 2, 3};
          System.out.println(myNumbers[10]);
        } catch (Exception e) {
          System.out.println("Something went wrong.");
        }
      }
    }
    
  • finally

    finally语句使您可以在try...catch之后执行代码,而不管结果如何:
    public class MyClass {
      public static void main(String[] args) {
        try {
          int[] myNumbers = {1, 2, 3};
          System.out.println(myNumbers[10]);
        } catch (Exception e) {
          System.out.println("Something went wrong.");
        } finally {
          System.out.println("The 'try catch' is finished.");
        }
      }
    }