日期:2014-05-20  浏览次数:20699 次

异常问题..来解决哈..初学
(1)找出下面程序的错误并更正(提示:共有5处错误)。
public   class   MyClass
{
            public   static   void   main(String   args[])
            {
                    myMethod();
            }
            public   void   myMethod()   throw   MyException
            {
                    throws   (new   MyException());
            }
}
class   MyException
{
            public   String   toString()
            {
                    return   ( "用户自定义的异常 ");
            }
}

我修改了几处,以下的就不对拉.....
public   class   MyClass
{
            public   static   void   main(String   args[])throws   Exception
            {
                    myMethod();
            }
            public   static   void   myMethod()   throws   Exception
            {
                    try{
                    throw   (new   MyException());
                          }catch(Exception   e){
                          System.out.println(e.getMessage());
                          }  
            }
}
class   MyException
{
            public   String   toString()
            {
                    return   ( "用户自定义的异常 ");
            }
}



------解决方案--------------------
public class MyClass
{
public static void main(String args[])
{
new MyClass().myMethod();
}
public void myMethod() throw MyException
{
throw new MyException();
}
}
class MyException
{
public String toString()
{
return ( "用户自定义的异常 ");
}
}

------解决方案--------------------
你的MyException根本就不是一个异常,因为没有继承自Exception或者它的任何一个子类。
你的代码可以改成:

public class MyClass {
public static void main(String args[]) {
myMethod();
}

public static void myMethod() {
try {
throw (new MyException());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

class MyException extends Exception {