在学习Java异常处理的过程中,按照课本(《Java程序设计完全自学手册》)的一个例子来写
package test;
class MyException extends Exception{
String message;
public MyException(String ErrorMessagr){
message=ErrorMessagr;
}
public MyException(){}
public String getMessage(){
return message;
}
}
import java.util.Scanner;
public class TestThrows {
public void print() throws MyException{
Scanner scanner = new Scanner(System.in);
System.out.println("Please input Positive");
String str=scanner.next();
int i = Integer.parseInt(str);
if (i>0){
System.out.print(i);}
else if (i<0){
throw new MyException("DO NOT input Negative");}
else{
throw new MyException("astr");}
}
public static void main(String[] args) {
TestThrows testThrows=new TestThrows();
try {
testThrows.print();}
catch (MyException e){
e.printStackTrace();}
catch (NumberFormatException n){
System.out.println("The number format is incorrect");
}
}
}
期待的结果是根据键盘输入来做出判断。
但是在编译中,红色字体部分上报错误
- Syntax error on token(s), misplaced construct(s)
- The serializable class MyException does not declare a static final serialVersionUID field of type long
执行也会出错
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at test.TestThrows.main(TestThrows.java:64)
自己通过baidu找不到合适的答案,请大家帮我看看究竟是哪里出问题了,谢谢。
------解决方案--------------------
把import 语句放在package下面
- Java code
[color=#FF0000]package test;import java.util.Scanner;[/color]class MyException extends Exception{ String message; public MyException(String ErrorMessagr){ message=ErrorMessagr; } public MyException(){} public String getMessage(){ return message; } } public class TestThrows { public void print() throws MyException{ Scanner scanner = new Scanner(System.in); System.out.println("Please input Positive"); String str=scanner.next(); int i = Integer.parseInt(str); if (i>0){ System.out.print(i);} else if (i<0){ throw new MyException("DO NOT input Negative");} else{ throw new MyException("astr");} } public static void main(String[] args) { TestThrows testThrows=new TestThrows(); try { testThrows.print();} catch (MyException e){ e.printStackTrace();} catch (NumberFormatException n){ System.out.println("The number format is incorrect"); } } }
------解决方案--------------------
要使用外部类,有两种方法:
1. import语句,放在源文件程序代码最开始的部分。就是声明类之前。这应该是java的语言规范吧。
2. 不使用import语句,这时需要打出该类的完整名称,比如你用到的Scanner类,就得些称这样:
java.util.Scanner scanner = new java.util.Scanner(System.in);