Java中RuntimeException和Exception
在java的异常类体系中,Error和RuntimeException是非检查型异常,其他的都是检查型异常。
所有方法都可以在不声明throws的情况下抛出RuntimeException及其子类
不可以在不声明的情况下抛出非RuntimeException
简单的说,非RuntimeException必要自己写catch块处理掉。
RuntimeException不用try catch捕捉将会导致程序运行中断,若用则不会中断
1.RuntimeException
今天摩根IT电面的时候被问到Exception和RuntimeException的区别,当时答不出来,大囧,晚上来学习一下。
首先看一段代码,主要内容就是将字符串类型的数字转化为整型的数字,然后让两个数字相乘,代码如下:
public class RuntimeException { public static void main(String[] args) {
// TODO Auto-generated method stub
String str="123";
int temp=Integer.parseInt(str);
System.out.println(temp*temp);
}
}
产看parseInt方法的源代码如下:
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
我们发现这个方法中抛出了NumberFormatException异常,但是在上面的代码中我们没有找到try...catch来处理,这是为什么呢。按照我们异常处理的知识,如果一个方法通过throws抛出了异常,那么可以在抛出异常的方法中不适用try...catch,但是在调用这个方法的地方必须有try...catch来处理。
下面来观察NumberFormatException类的继承关系:
从上图我们可以发现NumberFormatException是RuntimeException的子类,那么这就需要我们清楚Exception和RuntimeException的概念:
- Exception:在程序中必须使用try...catch进行处理。
- RuntimeException:可以不使用try...catch进行处理,但是如果有异常产生,则异常将由JVM进行处理。
对于RuntimeException的子类最好也使用异常处理机制。虽然RuntimeException的异常可以不使用try...catch进行处理,但是如果一旦发生异常,则肯定会导致程序中断执行,所以,为了保证程序再出错后依然可以执行,在开发代码时最好使用try...catch的异常处理机制进行处理。
2.User Defined Exception
下面给出一个自定义异常的实例
class MyException extends Exception{
public MyException(String msg){
super(msg);
}
} public class DefaultException { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
throw new MyException("自定义异常");
}catch(Exception e){
System.out.println(e);//edu.sjtu.ist.comutil.MyException: 自定义异常
//System.err.println(e);
// e.printStackTrace();
// StackTraceElement[] sts = e.getStackTrace();
// for (StackTraceElement st : sts){
// System.err.println(st);
// } // System.err.println(e.getStackTrace());
} } }
class MyException extends Exception{
public MyException(String msg){
super(msg);
}
} public class DefaultException { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
throw new MyException("自定义异常");
}catch(Exception e){
System.out.println(e);//edu.sjtu.ist.comutil.MyException: 自定义异常
//System.err.println(e);
// e.printStackTrace();
// StackTraceElement[] sts = e.getStackTrace();
// for (StackTraceElement st : sts){
// System.err.println(st);
// } // System.err.println(e.getStackTrace());
} } }
class MyException extends Exception{
public MyException(String msg){
super(msg);
}
} public class DefaultException { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
throw new MyException("自定义异常");
}catch(Exception e){
System.out.println(e);//edu.sjtu.ist.comutil.MyException: 自定义异常
//System.err.println(e);
// e.printStackTrace();
// StackTraceElement[] sts = e.getStackTrace();
// for (StackTraceElement st : sts){
// System.err.println(st);
// } // System.err.println(e.getStackTrace());
} } }
输出结果为:
MyException: 自定义异常
常见的RuntimeException- -
RuntimeException是开发中最容易遇到的,下面列举一下常见的RuntimeException:
1、NullPointerException:见的最多了,其实很简单,一般都是在null对象上调用方法了。
String s=null;
boolean eq=s.equals(""); // NullPointerException
这里你看的非常明白了,为什么一到程序中就晕呢?
public int getNumber(String str){
if(str.equals("A")) return 1;
else if(str.equals("B")) return 2;
}
这个方法就有可能抛出NullPointerException,我建议你主动抛出异常,因为代码一多,你可能又晕了。
public int getNumber(String str){
if(str==null) throw new NullPointerException("参数不能为空");
//你是否觉得明白多了
if(str.equals("A")) return 1;
else if(str.equals("B")) return 2;
}
2、NumberFormatException:继承IllegalArgumentException,字符串转换为数字时出现。比如int i= Integer.parseInt("ab3");
3、ArrayIndexOutOfBoundsException:数组越界。比如 int[] a=new int[3]; int b=a[3];
4、StringIndexOutOfBoundsException:字符串越界。比如 String s="hello"; char c=s.chatAt(6);
5、ClassCastException:类型转换错误。比如 Object obj=new Object(); String s=(String)obj;
6、UnsupportedOperationException:该操作不被支持。如果我们希望不支持这个方法,可以抛出这个异常。既然不支持还要这个干吗?有可能子类中不想支持父类中有的方法,可以直接抛出这个异常。
7、ArithmeticException:算术错误,典型的就是0作为除数的时候。
8、IllegalArgumentException:非法参数,在把字符串转换成数字的时候经常出现的一个异常,我们可以在自己的程序中好好利用这个异常。
最新文章
- sublime text 3 配置php开发环境
- C#并行编程之数据并行
- 激!GSS系列
- 【Git】标签管理
- Java签名
- sql server:compare data from two tables
- 我、实战nginx+naxsi(WAF)之一
- 【网络流24题】No.1 搭配飞行员(飞行员配对方案问题)
- NodeJs读取源代码使用的字符集
- selenium webdriver python 开始
- Web颜色搭配 - 收集
- VBOX安装Centos设置分辨率为1366x768[已解决]
- openstack controller ha测试环境搭建记录(二)——配置corosync和pacemaker
- VB6之图像灰度与二值化
- FFT模板(多项式乘法)
- redis安装异常的解决的办法
- UR机械臂运动学正逆解方法
- three.js使用base64 图片创建Texture纹理
- Python 使用ctypes调用 C 函数
- Spark性能优化指南——基础篇转
热门文章
- JDBC 学习复习6 学习与编写数据库连接池
- pytorch中使用多显卡训练以及训练时报错:expect more than 1 value per channel when training, got input size..
- TreeMap源码实现类中文全解析
- ASE19团队项目 beta阶段 model组 scrum6 记录
- 【Distributed】分布式配置中心
- Cannot determine value type from string 'xxxxxx'
- C#的预处理指令
- Django drf:cbv(class base view)源码分析
- python自动生成Docx(docxtpl库)
- Linux下zookeeper集群搭建