JAVA中的自定义异常有什么用啊。
可不可以请各位高手举个例子给我看看,谢谢了。

解决方案 »

  1.   

    当你决定用异常来处理错误时,就有用了。比如,你要给一个Man类的对象,和一个Woman类的对象做配对,配对前要检查年龄,如果男人年龄小于22,或者女人年龄小于20,就抛出一个异常,你可以把这个异常叫做TooYoungException。
      

  2.   

    Exception和Error类提供的内置异常不一定总能捕获程序中的错误。所以才要用到自定义的异常类啊。class MyException extends Exception
    {
    MyException()
    {
    System.out.println ("此部门不存在!!!");
    }
    }class TestException
    {
    protected TestException(){}

    public static void main(String[] args)
    {
    int empId,depId;
    String empName;

    try
    {
    empId=Integer.parseInt(args[0]);
    empName=args[1];
    depId=Integer.parseInt(args[2]);

    if(depId>5)
    {
    throw new MyException();
    }
    else{
    System.out.println ("雇员编号是:"+empId);
    System.out.println ("雇员姓名是:"+empName);
    System.out.println ("部门编号是:"+depId);
    }
    }catch(MyException me){
    System.out.println ("数据无效!");
    }catch(NumberFormatException ne){
    System.out.println ("数据错误!");
    }catch(ArrayIndexOutOfBoundsException ae){
    System.out.println ("数据不完整!");
    }
    }
    }
      

  3.   

    即便是这样,我也没有必要写一个自定义异常啊。
    我也可以写:
    throw new Exception("部门不存在啊")