Java异常类

1.     异常的分类

与异常有关的类的分类和层次关系如下

*******************************************************************************

Throwable

        Error

               VirtualMachineError

                      StackOverflowError

                      OutOfMemoryError

               AWTError

        Exception

               IOException

                      EOFException

                      FileNotFoundException

               RuntimeException %我们常说的异常类指的是这些 异常类

                      ArithmeticException

                      NullPointerException

                             ……

                      ArrayOutOfBoundsException

***************************************************************


2.     try-catch-finally语句

try-catch-finally语句的用法结构如下

********************************************************************

try{

        1.需要检测是否有异常的语句

}catch(Exception e){

        2.出现错误之后执行的语句

}finally{

        3.在2执行完毕之后,finally里面的语句一定会执行.

}

*******************************************************************

其中finally部分可以缺省.

例如

package com.exceptiontest.www;

public class SingleTest {
	public static void main(String args[]){
		int a[] = new int[]{1,2,3};
		try{
			a[3] = 1;
		}catch(ArrayIndexOutOfBoundsException e){
			e.printStackTrace();
			System.out.println("数组下标越界...");
		}finally{
			System.out.println("finally这段话可以不用写");
		}
	}
}

其运行结果如下



3.     自定义异常类以及throw-throws关键字

自定义异常类及其使用步骤如下

①定义异常类

定义类UDException(User-Defined-Exception)继承自Exception类,重新构造方法、printStackTrace()方法、getString()方法等方法或添加新的方法.

②使用异常类

在一个方法中的书写过程中,通过throws关键字,在方法名后添加[throws UDException],通过throw关键字,在方法体中需要抛出异常的未知添加[throw new UDException(?)],?为这个异常类的构造方法需要的参数.

例如

先定义一个IDNumberException类继承自Exception类

package com.exceptiontest.www;

import java.lang.Exception;

public class IDNumberException extends Exception{
	String message;
	public IDNumberException(String id){
		message = id;
	}
	public void printStackTrace(){
		System.out.println("身份证号码必须是18位,"+message+"不符合这个要求.");
	}
}

再在一个方法Input()中使用这个异常类

package com.exceptiontest.www;

import java.util.Scanner;

public class AsMain {
	public static void main(String args[]) throws IDNumberException{
		try{
			Input();
		}catch(IDNumberException e){
			e.printStackTrace();
		}
	}
	
	public static void Input() throws IDNumberException{
		Scanner s = new Scanner(System.in);
		String str = s.nextLine();
		if(str.length()!=18)
			throw new IDNumberException(str);
		else
			System.out.println("您当前输入的身份证号码为:"+str);
	}
}

运行输入123456789的结果如下


运行输入123456789987654321的结果如下


原文地址:https://www.cnblogs.com/tensory/p/6590776.html