java1234开源博客系统
博客信息

Java异常处理-throws和throw关键字

0
发布时间:『 2016-10-25 11:38』  博客类别:Java核心基础  阅读(6995) 评论(0)

Java异常处理-throws和throw关键字


throws表示当前方法不处理异常,而是交给方法的调用出去处理;

throw表示直接抛出一个异常;


我们来写下实例:

package com.java1234.chap04.sec03;

public class Demo1 {

	/**
	 * 把异常向外面抛
	 * @throws NumberFormatException
	 */
	public static void testThrows()throws NumberFormatException{
		String str="123a";
		int a=Integer.parseInt(str);
		System.out.println(a);
	}
	
	public static void main(String[] args) {
		try{
			testThrows();	
			System.out.println("here");
		}catch(Exception e){
			System.out.println("我们在这里处理异常");
			e.printStackTrace();
		}
		System.out.println("I'm here");
	}
}

这里我们直接把异常抛出了。


运行输出:

我们在这里处理异常
java.lang.NumberFormatException: For input string: "123a"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at com.java1234.chap04.sec03.Demo1.testThrows(Demo1.java:11)
	at com.java1234.chap04.sec03.Demo1.main(Demo1.java:17)
I'm here


throw表示直接抛出一个异常;

我们可以根据业务在代码任何地方抛出异常:

package com.java1234.chap04.sec03;

public class Demo2 {

	public static void testThrow(int a) throws Exception{
		if(a==1){
			// 直接抛出一个异常类
			throw new Exception("有异常");
		}
		System.out.println(a);
	}
	
	public static void main(String[] args) {
		try {
			testThrow(1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

运行输出:

java.lang.Exception: 有异常
	at com.java1234.chap04.sec03.Demo2.testThrow(Demo2.java:8)
	at com.java1234.chap04.sec03.Demo2.main(Demo2.java:15)


关键字:   java     异常  
关注Java1234微信公众号
博主信息
Java1234_小锋
(知识改变命运,技术改变世界)
Powered by Java1234 V3.0 Copyright © 2012-2016 Java知识分享网 版权所有