java中的异常——概念和常规处理

 

java中异常的种类有很多,这里就不一一讨论了。

异常就好比生活中的交通事故,需要try-catch这个交警来处理!

上代码:

 

public class ExceptionTry {

	public static void main(String[] args) {
		String str="123a";
		int a=Integer.parseInt(str);
		System.out.println(a);
		System.out.println("继续执行");
	}
}

//output:

java中的异常——概念和常规处理_第1张图片
程序执行的结果可以看出,控制台会输出异常的位置,并且遇到异常之后就不会继续执行了。

 

 

这时我们用try-catch来试一试:

public class ExceptionTry{
	 
    public static void main(String[] args) {
        String str="123a";
        try{
            int a=Integer.parseInt(str);          
        }catch(NumberFormatException e){
            e.printStackTrace();
        }
        System.out.println("继续执行");
    }
}

//output:

java中的异常——概念和常规处理_第2张图片
 

这时我们会发现,在可能出现异常的地方,加try,然后catch捕获异常,最后的还会继续执行之后的代码。

其中catch中NumberFormatException是异常的类型。

通过查看jdk API,我们发现Exception是异常类的老祖宗,所以在一般的开发中,直接用Exception。

 

在捕获异常的时候,假如我们不确定会抛出什么异常,我们可以写多个异常捕获。

 

public class Demo1 {

	public static void main(String[] args) {
		String str="123a";
		try{
			int a=Integer.parseInt(str);			
		}catch(NumberFormatException e){
			e.printStackTrace();
		}catch(NullPointerException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
		System.out.println("继续执行");
	}
}

但要注意的是:由上往下的异常,必须范围同级别或者更高;否则编译报错;

 

 

有时候在程序中,要保证有得代码必须执行,finally就派上用场了(如果有return,代码会终止,大家可以自己试一下)

 

public class Demo2 {

	public static void testFinally(){
		String str="123a";
		try{
			int a=Integer.parseInt(str);	
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("exception");
			return;
		}finally{
			System.out.println("finally end");
		}
		System.out.println("The end");
	}
	
	public static void main(String[] args) {
		testFinally();
	}
}

//output:

 

java中的异常——概念和常规处理_第3张图片
 

这里我们会发现,无论有没有异常,finally中都能执行。

你可能感兴趣的:(java中的异常——概念和常规处理)