我试图反序列化代码,并且在我的一个try-catch语句中不断收到错误。
import java.io.IOException;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class CalendarChecker
{
public static void main( String[] args )
{
Event party = null;
Event test = null;
ObjectInputStream input = null;
try{
input = new ObjectInputStream(new FileInputStream("myFile.txt"));
}
catch {
party = (Event)input.readObject();
test = (Event)input.readObject();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
try{
input.readObject();
input.readObject();
}
catch (IOException e){
e.printStackTrace();
}
try {
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println( party.getName() );
System.out.println( party.getDate() );
System.out.println( party.getLocation() );
System.out.println( party.getDescription() );
System.out.println( test.getName() );
System.out.println( test.getDate() );
System.out.println( test.getLocation() );
System.out.println( test.getDescription() );
}
}
每当我去编译它时,这就是我得到的错误:
CalendarChecker.java:19: error: '(' expected
catch {
^
CalendarChecker.java:19: error: illegal start of type
catch {
^
CalendarChecker.java:20: error: ')' expected
party = (Event)input.readObject();
^
CalendarChecker.java:20: error: not a statement
party = (Event)input.readObject();
任何指针都会非常感激。
答案 0 :(得分:1)
第一个catch
块缺少其参数。这是(...)
部分,指示程序关于要捕获的内容
https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
答案 1 :(得分:1)
Catch statemenents需要捕获异常。
try{
input = new ObjectInputStream(new FileInputStream("myFile.txt"));
}
catch {
party = (Event)input.readObject();
test = (Event)input.readObject();
}
需要采用
的形式try {
// try something
}
catch (Exception e) {
// do something with it
}
答案 2 :(得分:1)
catch {
这不是合法的语法。 catch
语句需要Throwable
参数。
然而,无论如何它都是糟糕的代码。不要写这样的代码。这是毫无意义。取决于try
块中先前代码成功的代码应位于try
块内。您只需要一个try/catch
用于主代码,另一个用于finally
块以确保关闭。并且您在catch
块中有代码,根本不应该存在。所有你需要的是这样的:
public static void main( String[] args )
{
ObjectInputStream input = null;
try{
input = new ObjectInputStream(new FileInputStream("myFile.txt"));
Event party = (Event)input.readObject();
Event test = (Event)input.readObject();
System.out.println( party.getName() );
System.out.println( party.getDate() );
System.out.println( party.getLocation() );
System.out.println( party.getDescription() );
System.out.println( test.getName() );
System.out.println( test.getDate() );
System.out.println( test.getLocation() );
System.out.println( test.getDescription() );
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
finally
{
try {
if (input != null)
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}