Java 处理未检查异常
异常是在程序实现过程中(即在运行时)发生的意外情况,中断程序的正常工作。
它可能发生的原因包括用户输入的非法内容、设备故障、网络连接丢失、物理限制、代码错误、尝试打开不可用文件等。
异常分为两大类:
- 已检查异常
- 
未检查异常 
在这里,我们将处理未检查的异常。
未检查异常还包括以下几种:
- Error类异常 - OutOfMemoryError异常、StackOverflow异常等
- 
运行时异常类 - Nullpointer异常、IndexoutOfBoundException异常等 
我们将学习处理这两种最常见的异常类型。这些异常是 Nullpointer异常 和 IndexoutOfBoundException异常。
IndexoutOfBoundException异常
当程序员试图检索索引大于或等于数组长度(因为数组的索引从0开始)的元素时,会出现此异常。当遇到此异常时,程序会自动结束。
示例1
import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args){
      //creation of an array of length 6 
      int arr[] = { 40, 32, 33, 14, 56, 90 };
      // Trying to retrieve an element greater than
      // index size of the array
      System.out.println(arr[10]);
   }
}
输出
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 6
    at ExceptionExample1.main(ExceptionExample1.java:8)
示例2
当用户尝试检索等于数组索引大小的数组元素时。
import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args){
      //creation of an array of length 6
      int arr[] = { 40, 32, 33, 14, 56, 90 };
      // Trying to retrieve an element equal to the
      // index size of the array
      System.out.println(arr[6]);
   }
}
输出
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
    at ExceptionExample1.main(ExceptionExample1.java:8)
处理ArrayIndexoutOfBoundException
该异常可以通过 try-catch 语句处理。
try语句允许程序员定义一段代码块来测试可能发生的错误,而catch块则捕获给定的异常对象并执行所需的操作。因此,程序将成功执行,而不会如上述情况那样意外停止。
示例
import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args) {
      // Filling the array with 6 array elements
      int arr[] = { 40, 32, 33, 14, 56, 90 };
      // Try block for exceptions
      try {
         // trying to retrieve and print the
         // element that is out of the scope of indexes of this array
         System.out.println(arr[10]);
      }
      // Catch block to catch the exceptions
      catch (ArrayIndexOutOfBoundsException e) {
         // displaying message when index which is not
         // present in an array is being accessed
         System.out.println(
         "Array Out of index please rectify your code");
      }
   }
}
输出
Array Out of index please rectify your code
空指针异常
当尝试检索具有空值的对象引用时会遇到此异常。
示例
import java.io.*;
public class ExceptionExample2 {
   public static void main(String[] args) {
      // Instance of string str has a null value
      String str = null;
      // Comparison of the null value with the other string
      // throws an exception and prints the same
      System.out.println(str.equals("Hello"));
   }
}
输出
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "" is null
    at ExceptionExample2.main(ExceptionExample2.java:8)
处理NullPointerException异常
这个异常也可以通过try-catch语句来处理。
示例
import java.io.*;
public class ExceptionExample2 {
   public static void main(String[] args) {
      // Assigning NULL value to a string
      String str = null;
      try {
         // Trying to compare the null value with another string
         // and throw an exception
         if (str.equals("Hello")) {
            // print the following string if it is true
            System.out.println("TRUE");
         }
      }
      catch (NullPointerException e) {
         // dealing with the exception
         System.out.println("Object Reference can't be null");
      }
   }
}
输出
Object Reference can't be null
在本教程中,我们讨论了处理未检查异常-NullpointerException和IndexoutOfBoundException的Java程序。
 极客笔记
极客笔记