首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

错误有关问题..来解决哈..初学

2011-11-28 
异常问题..来解决哈..初学(1)找出下面程序的错误并更正(提示:共有5处错误)。publicclassMyClass{publicstat

异常问题..来解决哈..初学
(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 {


public String toString() {
return ( "用户自定义的异常 ");
}
}


或者:


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

public static void myMethod() throws Exception {
throw (new MyException());
}
}

class MyException extends Exception {
public String toString() {
return ( "用户自定义的异常 ");
}
}
[解决办法]
MyMethod方法为静态
throws Exception
throw new Exception
//在自定义的异常中
class MyException extends Exception{
public MyException(String message){
super(message);
}
}

热点排行