Skip to content

Latest commit

 

History

History
161 lines (125 loc) · 3.97 KB

45.md

File metadata and controls

161 lines (125 loc) · 3.97 KB

Java 异常处理

原文: https://beginnersbook.com/2013/04/exception-handling-examples/

在本教程中,我们将看到几个常用异常的示例。如果您正在寻找异常处理教程,请参阅此完整指南:Java 中的异常处理

示例 1:算术异常

类:Java.lang.ArithmeticException 这是java.lang包中的内置类。当整数除以零时会发生此异常。

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");
      }
   }
}

以上程序的输出:

You Shouldn't divide a number by zero

**说明:**在上面的例子中,我将整数除以零,因此抛出ArithmeticException

示例 2:ArrayIndexOutOfBounds异常

类:Java.lang.ArrayIndexOutOfBoundsException 当您尝试访问不存在的数组索引时,会发生此异常。例如,如果数组只有 5 个元素,并且我们试图显示第 7 个元素,那么它将抛出此异常。

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");
      }
   }
}

输出:

ArrayIndexOutOfBounds

在上面的示例中,数组被初始化为仅存储 10 个元素索引 0 到 9.因为我们尝试访问索引 11 的元素,所以程序抛出此异常。

示例 3:NumberFormatException

分类:Java.lang.NumberFormatException

将字符串解析为任何数字变量时会发生此异常。

例如,语句int num=Integer.parseInt ("XYZ");将抛出NumberFormatException,因为String "XYZ"无法解析为int

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");
       }
   }
}

输出:

Number format exception occurred

示例 4:StringIndexOutOfBound异常

分类:Java.lang.StringIndexOutOfBoundsException

  • 每当调用一个不在范围内的字符串的索引时,就会创建此类的对象。
  • 字符串对象的每个字符都存储在从 0 开始的特定索引中。
  • 要获得字符串的特定索引中存在的字符,我们可以使用java.lang.StringcharAt(int)方法,其中int参数是索引。

例如。

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!!");
       }
   }
}

输出:

13
StringIndexOutOfBoundsException!!

发生异常是因为String中没有引用的索引。

示例 5:NullPointer异常

类:Java.lang.NullPointer Exception 只要使用null对象调用成员,就会创建此类的对象。

class Exception2 
{
   public static void main(String args[])
   {
	try{
		String str=null;
		System.out.println (str.length());
	}
        catch(NullPointerException e){
		System.out.println("NullPointerException..");
	}
   }
}

输出:

NullPointerException..

这里,length()是函数,应该在对象上使用。但是在上面的示例中String对象str为空,因此它不是由于NullPointerException发生的对象。