java 自定义异常及其处理

/*
自定义异常
1、继承exception类
2、定义自定义类的构造函数(实参),super(name);相当于使用父类的构造方法;
*/
import java.io.*;

class DivisorIsZeroException extends Exception
{
    public DivisorIsZeroException(String name)
    {
        super(name);
    }
}

class A
{
    public int divide(int a, int b) throws DivisorIsZeroException
    {
        int m = 0;
        
        if (0 == b)
            throw  new DivisorIsZeroException("除数不能为零!");//看到throws里面定义自己需要对其用throw处理
        else
            m = a/b;
            
        return m;
    }
}




public class TestExcep
{
    public static void main(String[] args) throws IOException
    {
        A aa = new A();        
        
        try                                                       //看到throws 调用方法时中try   catch处理异常
        {
            aa.divide(6, 0);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }        
    }
}

 

posted @ 2018-07-25 16:51  zjkl_欧了  阅读(327)  评论(0编辑  收藏  举报