Java 内置异常与实例

Java 内置异常与实例

Java中的异常类型

内置异常是指Java库中所提供的异常。这些异常适合用来解释某些错误情况。下面是Java中重要的内置异常的列表。

内置异常的例子

  1. Arithmetic exception : 当一个算术运算中出现异常情况时,它就会被抛出。
// 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
  1. 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
  1. 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
  1. 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
  1. 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
  1. 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
  1. 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
  1. NullPointerException : 当引用一个空对象的成员时,会引发这个异常。空代表什么都没有
// 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..
  1. 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
  1. 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
  1. StackOverflowError
// 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
  1. 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
  1. ExceptionInInitializerError
    代码 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

解释:在执行静态变量赋值和静态块时,如果出现任何异常,就会出现上述异常。

  1. 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开发人员明确发生的,表示一个方法被调用时出现了不合法的Argument。

  1. IllegalThreadStateException
// 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开发者明确提出来的,表示一个方法在错误的时间被调用。

  1. AssertionError
// 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开发者明确提出,表示断言语句失败。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程