异常
异常有很多种类,是指程序运行过程中出现的错误,从而导致程序的中断。
其中Throwable是所有异常(Exception)和错误(Error)的共同的父类。
异常的分类
当你在编译过程中系统报出的错误,属于编译时异常。(受查异常,系统会在编译时,编译器会对他进行检查)
如果编译时系统没有报错,而在运行之后才报出错误属于运行时异常。(非受查异常,不能进行捕获,必须找到错误的位置进行修改)
对于异常的处理
1.上抛,把出现的异常抛出给上一级。先是抛给调用我的方法,然后继续上抛,到main方法之后上抛给jvm,终端运行。需注意,这种方式并没有去解决这个异常,他任然存在。下面做个测试。
package com.zhy.blog;
class MyException extends Exception{
private String name;
public MyException(){
}
public MyException(String name){
this.name = name;
}
}
//自定义异常类
public class Example {
public void show(int n) throws MyException{
if(n>0){
System.out.println("对了");
}
else{
System.out.println("中止在这一步吗");
throw new MyException(); //抛出异常。
}
}//继续往上抛
public static void main(String[] args) throws MyException{
Example ex = new Example();
ex.show(-1);
System.out.println("还在运行吗");
}
}
//中止在这一步吗
//Exception in thread "main" com.zhy.blog.MyException
// at com.zhy.blog.Example.show(Example.java:20)
// at com.zhy.blog.Example.main(Example.java:26)
可以看到在main方法中调用show()方法之后的System语句并没有生效,程序中止在了抛出异常之后。
2.使用try{}catch{}进行捕获,把异常捕获后进行处理。
package com.zhy.blog;
class MyException extends Exception{
private String name;
public MyException(){
}
public MyException(String name){
this.name = name;
}
}
//自定义异常类
public class Example {
public void show(int n) throws MyException{
if(n>0){
System.out.println("对了");
}
else{
System.out.println("中止在这一步吗");
throw new MyException(); //抛出异常。
}
}//继续往上抛
public static void main(String[] args) throws MyException{
Example ex = new Example();
try{
ex.show(-1);
System.out.println("捕获异常之后,这一步不会被执行");
}
catch(MyException e){
System.out.println("别往上抛了");
}
}
}
//中止在这一步吗
//别往上抛了
可以发现捕获异常处理之后,程序能够继续运行下去,但是在try{}中异常捕获之后的代码并没有继续运行下去,这时候如果想同时执行其他操作,而不写在catch{}中就必须用到finally{},
package com.zhy.blog;
class MyException extends Exception{
private String name;
public MyException(){
}
public MyException(String name){
this.name = name;
}
}
//自定义异常类
public class Example {
public void show(int n) throws MyException{
if(n>0){
System.out.println("对了");
}
else{
System.out.println("中止在这一步吗");
throw new MyException(); //抛出异常。
}
}//继续往上抛
public static void main(String[] args) throws MyException{
Example ex = new Example();
try{
ex.show(-1);
System.out.println("捕获异常之后,这一步不会被执行");
}
catch(MyException e){
System.out.println("别往上抛了");
}finally{
System.out.println("害嘿害");
}
}
}
//中止在这一步吗
//别往上抛了
//害嘿害