Java中的异常类型与示例
Java定义了与其各种类库相关的几种异常类型。 Java还允许用户定义自己的异常。
内置异常
内置异常是Java库中可用的异常。这些异常适用于解释某些错误情况。下面是Java中重要的内置异常的列表。
- 算术异常
当算术运算中发生异常情况时抛出它。 - ArrayIndexOutOfBoundsException
抛出它表示已使用非法索引访问了数组。索引为负数或大于或等于数组的大小。 - ClassNotFoundException
当我们尝试访问未找到定义的类时会引发此异常 - FileNotFoundException
当文件不可访问或未打开时会引发此异常。 - IO异常
当输入输出操作失败或中断时抛出 - 中断异常
当线程等待、休眠或进行某些处理并被中断时抛出。 - NoSuchFieldException
当类不包含指定的字段(或变量)时抛出 - NoSuchMethodException
访问未找到的方法时会抛出它。 - 空指针异常
引用空对象的成员时会引发此异常。 Null 代表什么都没有 - NumberFormatException
当方法无法将字符串转换为数字格式时会引发此异常。 - 运行时异常
这表示在运行时发生的任何异常。 - StringIndexOutOfBoundsException
它由 String 类方法抛出以指示索引为负数或大于字符串的大小
内置异常示例:
- 算术异常
Java
// 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");
}
}
}
Java
//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..");
}
}
}
Java
// 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");
}
}
}
Java
//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");
}
}
}
Java
// 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");
}
}
}
Java
// 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");
}
}
}
Java
// 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();
}
}
}
输出:
Can't divide a number by 0
- 空指针异常
Java
//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
// 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
//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
- 数字格式异常
Java
// 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
// 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 类的子类,所以用户也应该让他的类成为它的子类。这是这样做的:
class MyException extends Exception
- 我们可以在他自己的异常类中写一个默认构造函数。
MyException(){}
- 我们还可以创建一个以字符串为参数的参数化构造函数。
我们可以使用它来存储异常详细信息。我们可以从这里调用超类(异常)构造函数并将字符串发送到那里。
MyException(String str)
{
super(str);
}
- 要引发用户定义类型的异常,我们需要为其异常类创建一个对象并使用 throw 子句将其抛出,如:
MyException me = new MyException(“Exception details”);
throw me;
- 下面的程序说明了如何创建自己的异常类 MyException。
- 帐号、客户名称和余额金额的详细信息采用三个数组的形式。
- 在 main() 方法中,使用 for 循环显示详细信息。此时,检查是否在任何帐户中的余额金额小于帐户中的最低余额金额。
- 如果是这样,则引发 MyException 并显示一条消息“Balance amount is less”。
Java
// 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中的已检查异常与未检查异常
- 将基类和派生类作为异常捕获
- 异常处理测验