- Throwable的子类包含哪两类?简述Java Error类与Exception类的区别。
- Error:
致命 异常,标识系统发生了不可控的错误。程序无法处理,只能人工介入。例如,虚拟机产生了StackOverflowError,OutOfMemoryError。 - Exception:
非致命 异常。程序可处理。分为受编辑器检测的checked异常(受检异常)和不受编辑器检测的unchecked异常(非受检异常)。
- Exception又分为checked异常和unchecked异常。
- 受检异常(checked exception):
在编译时需要检查的异常,需要用try-catch或throws处理。
class A{
public static void main(String[]args){
try(Scanner sc=new Scanner(System.in)){
int a=sc.nextShort();
}catch (Exception e){
e.printStackTrace();
}
}
}
- 非受检异常(unchecked exception):
不需要在编译时处理的异常。在java中派生于Error和RuntimeException的异常都是unchecked exception。
class A{
public static void main(String[]args){
int []a;
System.out.println(a[0]);
}
}
- 请查阅资料,简述StackOverflowError和OutOfMemoryError两类错误的发生情形和原因。
StackOverflowError (栈溢出):
发生原因:如果程序使用的栈深度超过虚拟机分配给线程的栈大小时,抛出该错误。
OutOfMemoryError (内存溢出):
发生原因:如果程序在对应栈中无法申请到足够的内存空间,则抛出该错误。 - 异常处理的两种方式。
5. 选取RuntimeException类的五个子类,编写抛出并捕获上述子类异常的程序(例如算术异常,空指针异常,类转换异常,数组越界异常等)。
- EmptyStackException类 (空堆栈异常):
class A{
public static void main(String[]args){
Stackstack = new Stack();
try{
stack.pop();
}catch (Exception e){
e.printStackTrace();
}
}
}
- ArithmeticException类 (算术异常):
class A{
public static void main(String[]args){
try{
int a=1/0;
}catch (Exception e){
e.printStackTrace();
}
}
}
- NullPointerException类 (空指针异常):
class A{
public static void main(String[]args){
Scanner sc=null;
try{
sc.nextBoolean();
}catch (Exception e){
e.printStackTrace();
}
}
}
- ArrayIndexOutOfBoundsException类 (数组越界异常):
class A{
public static void main(String[]args){
int []a=new int[5];
try{
System.out.println(a[-1]);
}catch (Exception e){
e.printStackTrace();
}
}
}
- NegativeArraySizeException类 (数组大小为负异常):
class A{
public static void main(String[]args){
try{
int []a=new int[-1];
}catch (Exception e){
e.printStackTrace();
}
}
}
6. 根据某业务场景自定义一个异常类,并在某场景下抛出该异常对象。
public class yicang extends Exception{
yicang(String ms){
super(ms);
}
static void Throw() throws yicang {
int a=0,b=3;
if(a!=0) {
System.out.println(b/a);
}
else{
throw new yicang("除数不能为0");
}
}
public static void main(String []args) {
try
{Throw();}
catch(yicang e) {
e.printStackTrace();
}
}
7. 异常中的throws声明与throw语句的区别是什么?
throw:表示方法内抛出某种异常对象
throws:方法的定义上使用 throws 表示这个方法可能抛出某种异常
8. finally子句的作用是什么?
finally子句和 try-catch 捕获异常连用,用于捕获异常的结束工作。
正常情况一定会执行。如果虚拟机停止或出现问题或者程序存在死循环则不执行。



