Java中的异常类型与示例

2021年3月13日17:01:30 发表评论 643 次浏览

Java定义了几种与其各种类库相关的异常类型。 Java还允许用户定义自己的异常。

Java异常

内置异常

内置异常是Java库中可用的异常。这些异常适用于解释某些错误情况。以下是Java中重要的内置异常列表。

  1. ArithmeticException
    在算术运算中发生异常情况时, 将抛出该异常。
  2. ArrayIndexOutOfBoundsException
    抛出该错误以表明已使用非法索引访问了数组。索引为负或大于或等于数组的大小。
  3. ClassNotFoundException
    当我们尝试访问未找到其定义的类时引发此异常
  4. FileNotFoundException
    当文件不可访问或无法打开时, 引发此异常。
  5. IOException
    输入输出操作失败或中断时抛出
  6. InterruptedException
    当线程正在等待, 休眠或进行某些处理时, 将引发该异常, 并使其中断。
  7. NoSuchFieldException
    当类不包含指定的字段(或变量)时引发
  8. NoSuchMethodException
    访问未找到的方法时将抛出该错误。
  9. 空指针异常
    当引用空对象的成员时, 引发此异常。空代表什么都没有
  10. NumberFormatException
    当方法无法将字符串转换为数字格式时, 将引发此异常。
  11. RuntimeException
    这表示在运行时发生的任何异常。
  12. StringIndexOutOfBoundsException
    String类方法抛出该异常, 以指示索引比字符串的大小大

内置异常的示例:

算术异常

// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
     public static void main(String args[])
     {
         try {
             int a = 30 , b = 0 ;
             int c = a/b;  // cannot divide by zero
             System.out.println ( "Result = " + c);
         }
         catch (ArithmeticException e) {
             System.out.println ( "Can't divide a number by 0" );
         }
     }
}

输出如下:

Can't divide a number by 0

空指针异常

//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
     public static void main(String args[])
     {
         try {
             String a = null ; //null value
             System.out.println(a.charAt( 0 ));
         } catch (NullPointerException e) {
             System.out.println( "NullPointerException.." );
         }
     }
}

输出如下:

NullPointerException..

StringIndexOutOfBound异常

// Java program to demonstrate StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
     public static void main(String args[])
     {
         try {
             String a = "This is like chipping " ; // length is 22
             char c = a.charAt( 24 ); // accessing 25th element
             System.out.println(c);
         }
         catch (StringIndexOutOfBoundsException e) {
             System.out.println( "StringIndexOutOfBoundsException" );
         }
     }
}

输出如下:

StringIndexOutOfBoundsException

FileNotFound异常

//Java program to demonstrate FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
  class File_notFound_Demo {
  
     public static void main(String args[])  {
         try {
  
             // Following file does not exist
             File file = new File( "E://file.txt" );
  
             FileReader fr = new FileReader(file);
         } catch (FileNotFoundException e) {
            System.out.println( "File does not exist" );
         }
     }
}

输出如下:

File does not exist

NumberFormat异常

// Java program to demonstrate NumberFormatException
class  NumberFormat_Demo
{
     public static void main(String args[])
     {
         try {
             // "akki" is not a number
             int num = Integer.parseInt ( "akki" ) ;
  
             System.out.println(num);
         } catch (NumberFormatException e) {
             System.out.println( "Number format exception" );
         }
     }
}

输出如下:

Number format exception

ArrayIndexOutOfBounds异常

// Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
{
     public static void main(String args[])
     {
         try {
             int a[] = new int [ 5 ];
             a[ 6 ] = 9 ; // accessing 7th element in an array of
                       // size 5
         }
         catch (ArrayIndexOutOfBoundsException e){
             System.out.println ( "Array Index is Out Of Bounds" );
         }
     }
}

输出如下:

Array Index is Out Of Bounds

用户定义的异常

有时, Java中的内置异常无法描述某种情况。在这种情况下, 用户还可以创建称为"用户定义的例外"的例外。

按照以下步骤创建用户定义的异常。

用户应创建一个异常类作为Exception类的子类。由于所有异常都是Exception类的子类, 因此用户还应使其类成为其子类。可以这样完成:

class MyException extends Exception

我们可以在他自己的异常类中编写一个默认构造函数。

MyException(){}

我们还可以创建一个以字符串为参数的参数化构造函数。

我们可以使用它来存储异常详细信息。我们可以从中调用super class(Exception)构造函数并将字符串发送到那里。

MyException(String str)
{
   super(str);
}

要引发用户定义类型的异常, 我们需要为其异常类创建一个对象, 并使用throw子句将其抛出, 如下所示:

MyException me = new MyException("Exception details");
throw me;
  • 下面的程序说明了如何创建自己的异常类MyException。
  • 帐号, 客户名和余额的详细信息以三个数组的形式显示。
  • 在main()方法中, 使用for循环显示详细信息。此时, 将检查任何帐户中的余额是否少于要存入该帐户的最小余额。
  • 如果是这样, 则引发MyException并显示一条消息"余额不足"。
// Java program to demonstrate user defined exception
  
// This program throws an exception whenever balance
// amount is below Rs 1000
class MyException extends Exception
{
     //store account information
     private static int accno[] = { 1001 , 1002 , 1003 , 1004 };
  
     private static String name[] =
                  { "Nish" , "Shubh" , "Sush" , "Abhi" , "Akash" };
  
     private static double bal[] =
          { 10000.00 , 12000.00 , 5600.0 , 999.00 , 1100.55 };
  
     // default constructor
     MyException() {    }
  
     // parametrized constructor
     MyException(String str) { super (str); }
  
     // write main()
     public static void main(String[] args)
     {
         try  {
             // display the heading for the table
             System.out.println( "ACCNO" + "\t" + "CUSTOMER" +
                                            "\t" + "BALANCE" );
  
             // display the actual account information
             for ( int i = 0 ; i < 5 ; i++)
             {
                 System.out.println(accno[i] + "\t" + name[i] +
                                                "\t" + bal[i]);
  
                 // display own exception if balance < 1000
                 if (bal[i] < 1000 )
                 {
                     MyException me =
                        new MyException( "Balance is less than 1000" );
                     throw me;
                 }
             }
         } //end of try
  
         catch (MyException e) {
             e.printStackTrace();
         }
     }
}

运行时错误

MyException: Balance is less than 1000
    at MyException.main(fileProperty.java:36)

输出如下:

ACCNO    CUSTOMER    BALANCE
1001    Nish    10000.0
1002    Shubh    12000.0
1003    Sush    5600.0
1004    Abhi    999.0

相关文章:

  • Java中的已检查与未检查异常
  • 捕获基类和派生类为异常
  • 异常处理测验

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: