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

来源:互联网 发布:网络音乐产业发展现状 编辑:程序博客网 时间:2024/05/14 15:06
异常处理方式2

  1. 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 stubExceptionThrowDemo demo = new ExceptionThrowDemo();//demo.method();//若直接这样写 出现 Unhandled exception type Exceptiondemo.method();//因此需对该异常进行处理:两种方式,1.自己处理 2.向上抛出:main方法中抛出到最后就是虚拟机进行处理了}public void method () throws Exception{//告诉调用该方法这个其他方法,我这个方法会抛出异常System.out.println("hello");throw new Exception();//抛出一个异常对象,因为所有的一场都是异常}}

     

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

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

      2. /* 抛出的异常,编译不通过,因为异常的类型:--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();//抛出一个异常对象,因为所有的一场都是异常}
0 0
原创粉丝点击