📜  Java中的内置异常及示例

📅  最后修改于: 2022-05-13 01:55:51.943000             🧑  作者: Mango

Java中的内置异常及示例

Java中的异常类型

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

  1. 算术异常:在算术运算中发生异常情况时抛出。
    // 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
    
  2. ArrayIndexOutOfBounds Exception :抛出该异常表示已使用非法索引访问了数组。索引为负数或大于或等于数组的大小。
    // 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
  3. ClassNotFoundException :当我们尝试访问未找到定义的类时会引发此异常。
    // Java program to illustrate the 
    // concept of ClassNotFoundException
    class Bishal {
      
    } class Geeks {
      
    } class MyClass {
    public static void main(String[] args)
        {
            Object o = class.forName(args[0]).newInstance();
            System.out.println("Class created for" + o.getClass().getName());
        }
    }
    

    输出:

    ClassNotFoundException
  4. 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
  5. IOException :当输入输出操作失败或中断时抛出
    // Java program to illustrate IOException
    import java.io.*;
    class Geeks {
    public static void main(String args[])
        {
            FileInputStream f = null;
            f = new FileInputStream("abc.txt");
            int i;
            while ((i = f.read()) != -1) {
                System.out.print((char)i);
            }
            f.close();
        }
    }
    

    输出:

    error: unreported exception IOException; must be caught or declared to be thrown
    
  6. InterruptedException :当线程在等待、休眠或做一些处理时抛出,并被中断。
    // Java Program to illustrate 
    // InterruptedException
    class Geeks {
    public static void main(String args[])
        {
            Thread t = new Thread();
            t.sleep(10000);
        }
    }
    

    输出:

    error: unreported exception InterruptedException; must be caught or declared to be thrown
    
  7. NoSuchMethodException :访问未找到的方法时抛出 t。
    // Java Program to illustrate 
    // NoSuchMethodException
    class Geeks {
    public Geeks()
        {
            Class i;
            try {
                i = Class.forName("java.lang.String");
                try {
                    Class[] p = new Class[5];
                }
                catch (SecurityException e) {
                    e.printStackTrace();
                }
                catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
            catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
      
    public static void main(String[] args)
        {
            new Geeks();
        }
    }
    

    输出:

    error: exception NoSuchMethodException is never thrown 
    in body of corresponding try statement
    
  8. NullPointerException :引用空对象的成员时会引发此异常。 Null 代表什么都没有
    // 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..
    
  9. NumberFormatException :当方法无法将字符串转换为数字格式时引发此异常。
    // 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
    
  10. StringIndexOutOfBoundsException:它由 String 类方法抛出以指示索引为负数而不是字符串的大小。
    // 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
    

其他一些重要的例外

  1. ClassCastException
    // Java Program to illustrate
    // ClassCastException
    class Test {
    public static void main(String[] args)
        {
            String s = new String("Geeks");
            Object o = (Object)s;
            Object o1 = new Object();
            String s1 = (String)o1;
        }
    }
    

    输出:

    Exception in thread "main" java.lang.ClassCastException: 
    java.lang.Object cannot be cast to java.lang.String
    
  2. 堆栈溢出错误
    // Java Program to illustrate 
    // StackOverflowError
    class Test {
    public static void main(String[] args)
        {
            m1();
        }
    public static void m1()
        {
            m2();
        }
    public static void m2()
        {
            m1();
        }
    }
    

    输出:

    Exception in thread "main" java.lang.StackOverflowError
    
  3. NoClassDefFoundError
    // Java Program to illustrate
    // NoClassDefFoundError
    class Test //
        {
    public static void main(String[] args)
        {
            System.out.println("HELLO GEEKS");
        }
    }
    

    输出:

    Note: If the corresponding Test.class file is not found 
    during compilation then we will get Run-time Exception
    saying Exception in thread "main" java.lang.NoClassDefFoundError
    
  4. 异常初始化错误
    代码 1:
    // Java Program to illustrate 
    // ExceptionInInitializerError
    class Test {
        static int x = 10 / 0;
    public static void main(String[] args)
        {
        }
    }
    

    输出:

    Exception in thread "main" java.lang.ExceptionInInitializerError
    Caused by: java.lang.ArithmeticException: / by zero
    

    代码 2:

    // Java Program to illustrate 
    // ExceptionInInitializerError
    class Test {
        static
        {
            String s = null;
            System.out.println(s.length());
        }
    public static void main(String[] args)
        {
        }
    }
    

    输出:

    Exception in thread "main" java.lang.ExceptionInInitializerError
    Caused by: java.lang.NullPointerException
    

    解释 :只要在执行静态变量赋值和静态块时发生任何异常,就会发生上述异常。

  5. IllegalArgumentException
    // Java Program to illustrate 
    // IllegalArgumentException
    class Test {
    public static void main(String[] args)
        {
            Thread t = new Thread();
            Thread t1 = new Thread();
            t.setPriority(7); // Correct
            t1.setPriority(17); // Exception
        }
    }
    

    输出:

    Exception in thread "main" java.lang.IllegalArgumentException
    

    说明:异常由程序员或 API 开发人员显式发生,以指示已使用非法参数调用了方法。

  6. 非法线程状态异常
    // Java Program to illustrate 
    // IllegalStateException
    class Test {
    public static void main(String[] args)
        {
            Thread t = new Thread();
            t.start();
            t.start();
        }
    }
    

    输出:

    Exception in thread "main" java.lang.IllegalThreadStateException
    

    解释 :上述异常由程序员或 API 开发人员显式引发,表明在错误的时间调用了一个方法。

  7. 断言错误
    // Java Program to illustrate 
    // AssertionError
    class Test {
    public static void main(String[] args)
        {
            // If x is not greater than or equal to 10
            // then we will get the run-time exception
            assert(x >= 10);
        }
    }
    

    输出:

    Exception in thread "main" java.lang.AssertionError
    

    解释 :上述异常由程序员或 API 开发人员显式引发,表明断言语句失败。