读书人

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

发布时间: 2011-11-28 19:15:02 作者: rapoo

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

读书人网 >J2SE开发

热点推荐