我试图为JOptionePane
我的方法中每个可能的抛出返回一个消息对话框:
public void add_note(String note) throws FileNotFoundException, IOException, InvalidFormatException{
... content ...
}
有没有办法做到这一点?
你可以尝试类似的东西:
public void add_note(String note) throws FileNotFoundException, IOException, InvalidFormatException
{
try
{
...content...
}
catch(FileNotFoundException fnfEx)
{
throw new FileNotFoundException("File was not found");
}
catch(IOException ioEx)
{
throw new FileNotFoundException("I/O exception");
}
catch(InvalidFormatException invEx)
{
throw new FileNotFoundException("Invalid format errror");
}
}
您将所需消息放在新异常中的位置,然后在 JOptionPane 中打印异常消息。
我会建议你另一种方法,因为没有人提到它。我会使用 AOP 来捕获这些异常并显示给最终用户。您将编写一个简单的方面,并且不要将您的代码与 try 和 catch 块混淆。
这是此类方面的示例
@Aspect
public class ErrorInterceptor{
@AfterThrowing(pointcut = "execution(* com.mycompany.package..* (..))", throwing = "exception")
public void errorInterceptor(Exception exception) {
if (logger.isDebugEnabled()) {
logger.debug("Error Message Interceptor started");
}
// DO SOMETHING HERE WITH EXCEPTION
logger.debug( exception.getCause().getMessage());
if (logger.isDebugEnabled()) {
logger.debug("Error Message Interceptor finished.");
}
}
}
如果你不知道什么是 Aspect Oriented Programming 一定要去看看,这是一个非常强大的概念(就像 OOP 一样),花点时间学习一下。
如果要使用JOptionPane.showMessageDialog显示对话框,请执行以下操作:
public void add_note(String note){
try {
//code
} catch (FileNotFoundException | IOException | InvalidFormatException e) {
JOptionPane.showMessageDialog(frame, e.getMessage(), "Title", JOptionPane.ERROR_MESSAGE);
//manage the exception here
}
}
使用 Try-Catch 可以捕获任何异常并在发生异常时返回某些内容。您应该为所有案例执行此操作。
public void add_note(String note){
try {
//code
} catch (FileNotFoundException e) {
//return something
}
}
将您的代码包装在 try catch 中。每个异常类型的内部 catch 块抛出特定于每个异常的消息
不要抛出异常,而是在您的方法中单独处理每个异常:
public JOptionPane add_note(String note) {
try {
...
} catch (FileNotFoundException fnfe) {
return ...;
} catch (IOException ioe) {
return ...;
} catch (InvalidFormatException ife) {
return ...;
}
}