Java异常与错误列表

目录:
Java API 中的所有公共异常和错误,按包分组。

Package java­.lang
Package java­.util
Package java­.io
Package java­.awt
Package java­.awt­.color
Package java­.awt­.datatransfer

Java中的异常类型与示例

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

内置异常:

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

  1. ArithmeticException: 当算术运算发生异常情况时抛出。
  2. ArrayIndexOutOfBoundsException:抛出该异常以指示已使用非法索引访问了数组。索引为负数或大于或等于数组的大小。
  3. ClassNotFoundException: 当我们尝试访问未找到定义的类时引发此异常
  4. FileNotFoundException: 当文件不可访问或未打开时引发此异常。
  5. IOException: 当输入输出操作失败或中断时抛出
  6. InterruptedException: 当线程在等待、休眠或做一些处理时抛出,并被中断。
  7. NoSuchFieldException: 当类不包含指定的字段(或变量)时抛出
  8. NoSuchMethodException:访问未找到的方法时抛出。
  9. NullPointerException: 引用空对象的成员时引发此异常。Null 代表什么都没有
  10. NumberFormatException: 当方法无法将字符串转换为数字格式时引发此异常。
  11. RuntimeException: 这表示在运行时发生的异常。
  12. StringIndexOutOfBoundsException: 由 String 类方法抛出,指示索引为负数或大于字符串的大小
  13. IllegalArgumentException :当方法接收到不完全符合给定关系或条件的参数时,此异常将引发错误或错误语句。它属于未经检查的异常。 
  14. IllegalStateException :当应用程序中的特定操作未访问该方法时,此异常将引发错误或错误消息。它属于未经检查的异常。

内置异常示例

A. 算术异常

// 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

B. NullPointer 异常

//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..

C. 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

D. FileNotFoundException

//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

E. 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

F. 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

G. IO 异常 

// Java program to demonstrate IOException
class IOException_Demo {
 
    public static void main(String[] args)
    {
 
        // Create a new scanner with the specified String
        // Object
        Scanner scan = new Scanner("Hello Geek!");
 
        // Print the line
        System.out.println("" + scan.nextLine());
 
        // Check if there is an IO exception
        System.out.println("Exception Output: "
                           + scan.ioException());
 
        scan.close();
    }
}

输出:

Hello Geek! 
Exception Output: null

H. NoSuchMethod 异常 

// Java program to demonstrate NoSuchElementException
public class NoSuchElementException_Demo {
 
    public static void main(String[] args)
    {
 
        Set exampleleSet = new HashSet();
 
        Hashtable exampleTable = new Hashtable();
 
        exampleleSet.iterator().next();
          //accessing Set
       
        exampleTable.elements().nextElement();
          //accessing Hashtable
       
          // This throws a NoSuchElementException as there are
        // no elements in Set and HashTable and we are
        // trying to access elements
    }
}

I. IllegalArgumentException:该程序检查此人是否有资格投票。如果年龄大于或等于 18 则不会抛出任何错误。如果年龄小于 18 岁,则会在错误语句中引发错误。 

此外,我们可以指定“throw new IllegalArgumentException()”而不显示错误消息。我们还可以在 IllegalArgumentException() 中指定 Integer.toString(variable_name) ,它将打印不满足给定条件的参数名称。

/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
   public static void print(int a) 
    {
         if(a>=18){
          System.out.println("Eligible for Voting");
          }
          else{
    
          throw new IllegalArgumentException("Not Eligible for Voting");
                                    
          }
       
    }
    public static void main(String[] args) {
         GFG.print(14); 
    }
}

输出 : 

Exception in thread "main" java.lang.IllegalArgumentException: Not Eligible for Voting
at GFG.print(File.java:13)
at GFG.main(File.java:19)

J. IllegalStateException:此程序仅显示正整数的数字相加。如果两个数字都是正数,那么只有它会调用 print 方法来打印结果,否则它将抛出 IllegalStateException 并带有错误语句。在这里,该方法不适用于非正整数。

此外,我们可以指定“throw new IllegalStateException()”而不使用错误语句。

/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
      public static void  print(int a,int b)
     {
         System.out.println("Addition of Positive Integers :"+(a+b));
     }
     
    public static void main(String[] args) {
    int n1=7;
    int n2=-3;
     if(n1>=0 && n2>=0)
     {
         GFG.print(n1,n2);
     }
     else
     {
         throw new IllegalStateException("Either one or two numbers are not Positive Integer");
     }
    }
}

输出 :

Exception in thread "main" java.lang.IllegalStateException: Either one or two numbers are not Positive Integer
at GFG.main(File.java:20)

k. ClassNotFound Exception :

// Java program to demonstrate ClassNotFoundException
public class ClassNotFoundException_Demo
{
    public static void main(String[] args) {
        try{
            Class.forName("Class1");   // Class1 is not defined
        }
        catch(ClassNotFoundException e){
            System.out.println(e);
            System.out.println("Class Not Found...");
        }
    }
}

输出

java.lang.ClassNotFoundException: Class1 
Class Not Found...

用户定义的异常

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

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

  • 用户应该创建一个异常类作为异常类的子类。因为所有的异常都是 Exception 类的子类,所以用户也应该让他的类成为它的子类。这是这样做的: 
MyException 类扩展异常
  • 我们可以在他自己的异常类中写一个默认构造函数。 
MyException(){}
  • 我们还可以创建一个以字符串为参数的参数化构造函数。 
    我们可以使用它来存储异常详细信息。我们可以从这里调用超类(异常)构造函数并将字符串发送到那里。 
MyException(String str)
{
   super(str);
}
  • 要引发用户定义类型的异常,我们需要为其异常类创建一个对象并使用 throw 子句将其抛出,如下所示: 
MyException me = new MyException(“Exception details”);
throw me;
  • 以下程序说明了如何创建自己的异常类 MyException。
  • 帐号、客户名称和余额金额的详细信息采用三个数组的形式。
  • 在 main() 方法中,使用 for 循环显示详细信息。此时,如果任何帐户中的余额少于该帐户中的最小余额,则会进行检查。
  • 如果是这样,则引发 MyException 并显示一条消息“Balance amount is less”。

例子

// 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() {    }
 
    // parameterized 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 API 中的所有公共异常和错误,按包分组。

✔: 检查异常
<版本> : Since version

Package java­.lang

Package java­.util

Package java­.io

Package java­.awt

Package java­.awt­.color

Package java­.awt­.datatransfer

Package java­.awt­.dnd

Package java­.awt­.geom

Package java­.awt­.image

Package java­.awt­.print

Package java­.beans

Package java­.lang­.annotation

Package java­.lang­.instrument

Package java­.lang­.invoke

Package java­.lang­.module

Package java­.lang­.reflect

Package java­.net

Package java­.net­.http

Package java­.nio

Package java­.nio­.channels

Package java­.nio­.charset

Package java­.nio­.file

Package java­.nio­.file­.attribute

Package java­.rmi

Package java­.rmi­.activation

Package java­.rmi­.server

Package java­.security

Package java­.security­.acl

Package java­.security­.cert

Package java­.security­.spec

Package java­.sql

Package java­.text

Package java­.time

Package java­.time­.format

Package java­.time­.temporal

Package java­.time­.zone

Package java­.util­.concurrent

Package java­.util­.jar

Package java­.util­.prefs

Package java­.util­.regex

Package java­.util­.zip

Package com­.sun­.jdi

Package com­.sun­.jdi­.connect

Package com­.sun­.jdi­.connect­.spi

Package com­.sun­.jdi­.request

Package com­.sun­.nio­.sctp

Package com­.sun­.tools­.attach

Package javax­.annotation­.processing

Package javax­.crypto

Package javax­.imageio

Package javax­.imageio­.metadata

Package javax­.lang­.model

Package javax­.lang­.model­.element

Package javax­.lang­.model­.type

Package javax­.management

Package javax­.management­.modelmbean

Package javax­.management­.monitor

Package javax­.management­.openmbean

Package javax­.management­.relation

Package javax­.management­.remote

Package javax­.naming

Package javax­.naming­.directory

Package javax­.naming­.ldap

Package javax­.net­.ssl

Package javax­.print

Package javax­.print­.attribute

Package javax­.script

Package javax­.security­.auth

Package javax­.security­.auth­.callback

Package javax­.security­.auth­.login

Package javax­.security­.cert

Package javax­.security­.sasl

Package javax­.smartcardio

Package javax­.sound­.midi

Package javax­.sound­.sampled

Package javax­.sql­.rowset

Package javax­.sql­.rowset­.serial

Package javax­.sql­.rowset­.spi

Package javax­.swing

Package javax­.swing­.text

Package javax­.swing­.tree

Package javax­.swing­.undo

Package javax­.transaction­.xa

Package javax­.xml­.catalog

Package javax­.xml­.crypto

Package javax­.xml­.crypto­.dsig

Package javax­.xml­.datatype

Package javax­.xml­.parsers

Package javax­.xml­.stream

Package javax­.xml­.transform

Package javax­.xml­.validation

Package javax­.xml­.xpath

Package jdk­.dynalink

Package jdk­.jshell

Package jdk­.jshell­.spi

Package jdk­.nashorn­.api­.scripting

Package jdk­.nashorn­.api­.tree

Package jdk­.security­.jarsigner

Package netscape­.javascript

Package org­.ietf­.jgss

Package org­.w3c­.dom

Package org­.w3c­.dom­.events

Package org­.w3c­.dom­.ls

Package org­.w3c­.dom­.ranges

Package org­.w3c­.dom­.xpath

Package org­.xml­.sax