Java辨别 Java中Error错误和Exception异常有什么江湖恩怨吗?



Error表示系统级的错误和程序不必处理的异常,是恢复不是不可能但很困难的情况下的一种严重问题;比如内存溢出,不可能指望程序能处理这样的情况;

举例:

import java.util.ArrayList;
import java.util.List;
public class OutOfMemoryTest {
    public static void main(String[] args){
        List list=new ArrayList();
        for(;;){
            int[] tmp=new int[1000000];
            list.add(tmp);
        }
    }
}

报错:Exception in thread "main" java.lang.OutOfMemoryError: Java heap space


public class StackOverflowTest {
    public static void main(String[] args) {
        method();
    }
    public static void method(){
        for(;;)
            method();
    }
}

报错:Exception in thread "main" java.lang.StackOverflowError


Exception表示需要捕捉或者需要程序进行处理的异常,是一种设计或实现问题;也就是说,它表示如果程序运行正常,从不会发生的情况。

ArrayIndexOutOfBoundsException 数组下标越界异常,

public class StackOverflowTest {
public static void main(String[] args) {
int[] a = {1,2,3,4,5};
System.out.println(a[7]);
}
}

报错:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7

ArithmaticException 算数异常 如除数为零

public class StackOverflowTest {

public static void main(String[] args) {

System.out.println(1/0);
}
}

报错:Exception in thread "main" java.lang.ArithmeticException: / by zero

NullPointerException 空指针异常

public class StackOverflowTest {
public static void main(String[] args) {
String s = null;
System.out.println(s.toLowerCase());
}
}

报错:Exception in thread "main" java.lang.NullPointerException

IllegalArgumentException 不合法参数异常


拓展:

2005年摩托罗拉的面试中曾经问过这么一个问题“If a process reports a stack overflow run-time error, what’s the most possible cause?”,给了四个选项

a. lack of memory; 

b. write on an invalid memory space; 

c. recursive function calling; 

d. array index out of boundary. 

Java程序在运行时也可能会遭遇StackOverflowError,这是一个无法恢复的错误,只能重新修改代码了,这个面试题的答案是c。

如果写了不能迅速收敛的递归,则很有可能引发栈溢出的错误。


提示:用递归编写程序时一定要牢记两点:

1. 递归公式;

2. 收敛条件(什么时候就不再继续递归)。




 




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值