您的位置:首页 > 编程语言 > Java开发

Think in Java 笔记_Chapter12_1_Exception基础_异常处理2

2015-09-17 23:21 375 查看
异常处理方式2

throw向上抛出

package cn.seven.shengsiyuan.exception;

/*
 * 2015年04月05日13:05:35
 * Location:501
 * 
 * 异常处理方法2:抛出异常,由调用该方法的方法  进行处理该异常
 */
public class ExceptionThrowDemo {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub

		ExceptionThrowDemo demo = new ExceptionThrowDemo();
		//demo.method();//若直接这样写 出现 Unhandled exception type Exception
		demo.method();//因此需对该异常进行处理:两种方式,1.自己处理 2.向上抛出:main方法中抛出到最后就是虚拟机进行处理了
		
	
	}

	public void method () throws Exception{//告诉调用该方法这个其他方法,我这个方法会抛出异常
		
		
		System.out.println("hello");
		throw new Exception();//抛出一个异常对象,因为所有的一场都是异常
	}
}




有些异常 编译时候 可以通过,有些异常不可以通过,为何?

int a = 3;
int b = 0;
int c= a / b;//这里即使可能抛出异常,但是编译通过,运行时抛出异常`    
System.out.println("---hello---");


/* 

抛出的异常,编译不通过,因为异常的类型:
--CheckedException(非运行时异常),

在编译时候就需要进行处理_处理方式两种:
1,try{}catch{}

2, 在调用该会产生异常的方法 所在的方法声明 throws Exception
--对于UncheckedException(运行时异常),

如c=a/b;我们可以对其进行处理,也可以不处理,推荐不处理

*/
public static void main(String[] args)  {
	
	ExceptionThrowDemo demo = new ExceptionThrowDemo();
	demo.method();//若直接这样写 出现 Unhandled exception type Exception
	
	
	}

public void method () throws Exception{//告诉调用该方法这个其他方法,我这个方法会抛出异常
		
	System.out.println("method");
	throw new Exception();//抛出一个异常对象,因为所有的一场都是异常
		
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: