多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Java 异常处理 > 原文: [https://beginnersbook.com/2013/04/exception-handling-examples/](https://beginnersbook.com/2013/04/exception-handling-examples/) 在本教程中,我们将看到几个常用异常的示例。如果您正在寻找异常处理教程,请参阅此完整指南:[Java 中的异常处理](https://beginnersbook.com/2013/04/java-exception-handling/)。 ## 示例 1:算术异常 类:`Java.lang.ArithmeticException` 这是`java.lang`包中的内置类。当整数除以零时会发生此异常。 ```java class Example1 { public static void main(String args[]) { try{ int num1=30, num2=0; int output=num1/num2; System.out.println ("Result: "+output); } catch(ArithmeticException e){ System.out.println ("You Shouldn't divide a number by zero"); } } } ``` **以上程序的输出:** ```java You Shouldn't divide a number by zero ``` **说明:**在上面的例子中,我将整数除以零,因此抛出`ArithmeticException`。 ## 示例 2:`ArrayIndexOutOfBounds`异常 类:`Java.lang.ArrayIndexOutOfBoundsException` 当您尝试访问不存在的数组索引时,会发生此异常。例如,如果数组只有 5 个元素,并且我们试图显示第 7 个元素,那么它将抛出此异常。 ```java class ExceptionDemo2 { public static void main(String args[]) { try{ int a[]=new int[10]; //Array has only 10 elements a[11] = 9; } catch(ArrayIndexOutOfBoundsException e){ System.out.println ("ArrayIndexOutOfBounds"); } } } ``` **输出:** ```java ArrayIndexOutOfBounds ``` 在上面的示例中,数组被初始化为仅存储 10 个元素索引 0 到 9.因为我们尝试访问索引 11 的元素,所以程序抛出此异常。 ## 示例 3:`NumberFormatException` 分类:`Java.lang.NumberFormatException` 将字符串解析为任何数字变量时会发生此异常。 例如,语句`int num=Integer.parseInt ("XYZ");`将抛出`NumberFormatException`,因为`String "XYZ"`无法解析为`int`。 ```java class ExceptionDemo3 { public static void main(String args[]) { try{ int num=Integer.parseInt ("XYZ") ; System.out.println(num); }catch(NumberFormatException e){ System.out.println("Number format exception occurred"); } } } ``` 输出: ```java Number format exception occurred ``` ## 示例 4:`StringIndexOutOfBound`异常 分类:`Java.lang.StringIndexOutOfBoundsException` * 每当调用一个不在范围内的字符串的索引时,就会创建此类的对象。 * 字符串对象的每个字符都存储在从 0 开始的特定索引中。 * 要获得字符串的特定索引中存在的字符,我们可以使用[`java.lang.String`](https://beginnersbook.com/2013/12/java-strings/)的[`charAt(int)`方法](https://beginnersbook.com/2013/12/java-strings/),其中`int`参数是索引。 例如。 ```java class ExceptionDemo4 { public static void main(String args[]) { try{ String str="beginnersbook"; System.out.println(str.length());; char c = str.charAt(0); c = str.charAt(40); System.out.println(c); }catch(StringIndexOutOfBoundsException e){ System.out.println("StringIndexOutOfBoundsException!!"); } } } ``` 输出: ```java 13 StringIndexOutOfBoundsException!! ``` 发生异常是因为`String`中没有引用的索引。 ## 示例 5:`NullPointer`异常 类:`Java.lang.NullPointer Exception` 只要使用`null`对象调用成员,就会创建此类的对象。 ```java class Exception2 { public static void main(String args[]) { try{ String str=null; System.out.println (str.length()); } catch(NullPointerException e){ System.out.println("NullPointerException.."); } } } ``` 输出: ```java NullPointerException.. ``` 这里,`length()`是函数,应该在对象上使用。但是在上面的示例中`String`对象`str`为空,因此它不是由于`NullPointerException`发生的对象。