码迷,mamicode.com
首页 > 其他好文 > 详细

面向对象(throws和throw的区别)

时间:2014-09-29 15:49:01      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   使用   ar   sp   

bubuko.com,布布扣

/**
* Created by Administrator on 2014/9/29.
*
* throws和throw的区别
*
* throws使用在函数上,throw使用在函数内
*
* throws后面跟的是异常类,可以跟多个,用逗号连接
* throw后面跟的是异常对象
*/

//copyright?liupengcheng
//
http://www.cnblogs.com/liupengcheng
class fushuException extends Exception
{
    private int value;
    fushuException(String msg,int value)
    {
        super(msg);
        this.value = value;
    }
    public int getValue()
    {
        return value;
    }
}

//copyright?liupengcheng
//
http://www.cnblogs.com/liupengcheng

class Demo5
{
    int div(int a,int b)    throws fushuException //fushuException    自定义负数异常
    {
        if(b<0)
            throw new fushuException("出现了除数是负数的情况",b);
        return a/b;
    }
}

//copyright?liupengcheng
//
http://www.cnblogs.com/liupengcheng


public class ExceptionDemo3 {
    public static void main(String [] args)
    {
        Demo5 d = new Demo5();
        try
        {
            int x = d.div(4,-1);
            System.out.println("x"+ x);
        }
        catch(fushuException e)
        {
            System.out.println(e.toString());
            System.out.println("出现问题的数值是"+ e.getValue());
        }

        System.out.println("over");
    }
}

//copyright?liupengcheng
//
http://www.cnblogs.com/liupengcheng

面向对象(throws和throw的区别)

标签:style   blog   http   color   io   os   使用   ar   sp   

原文地址:http://www.cnblogs.com/liupengcheng/p/4000237.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!