我有一个接口(interface)类,一个实现类,一个异常类和主类。我不确定我的代码中是否有效地使用了 try catch block 。我在网上搜索并找到了类似的主题和问题,但我找不到问题的答案。我在主文件和实现文件中都使用了 try catch 。有道理吗? 您能建议一下有效性吗?下面关于 try-catch 的逻辑是否正确?
Interface Class:
public void createDatabase() throws DatabaseAlreadyCreated;
Implementation Class:
public void createDatabase() throws DatabaseAlreadyCreated
{
try
{
// Create Database
//if database is already exist
throw new DatabaseAlreadyCreated();
}
catch (SQLException e) {e.printStackTrace();}
catch (ClassNotFoundException e) {e.printStackTrace();}
}
Exception Class:
public class DatabaseAlreadyExist extends Exception
{
public DatabaseAlreadyExist(String str)
{
System.out.println("database exist exception");
}
}
Main Class:
public static void main(String args[])
{
try
{
x = ops.createDatabase();
}
catch (DatabaseAlreadyExist e)
{
e.printStackTrace();
}
}
最佳答案
代码有些损坏......除非您有非常具体的原因,否则您永远不应该直接扩展 Throwable
类,而应该扩展 Exception
(或后代)异常(如 RuntimeException)。
使用这样的代码,您不太可能捕获异常,除非您使用 catch (DatabaseAlreadyExistsException e) 显式捕获异常
除此之外,您还存在许多不建议的错误处理问题...执行“printStackTrace”并不是处理问题的有效方法,但我不确定您这样做是否只是为了表明您是否有处理它(即您的真实代码是否只执行 printStackTrace?)......
<小时/>编辑:评论后更新...
好吧,我现在比以前更明白你在问什么了。使用其他答案和评论中描述的机制,我建议这样做:
public boolean checkDatabaseExists(...) {
try {
... do the things you need to check the database exists.
return true;
} catch (Exception e) {
return false;
}
}
然后,在您的主要方法中,您可以:
if (!checkDatabaseExists(...)) {
createDatabase(...);
}
关于java - 有效使用 try-catch block 以及我们应该将它们放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19883350/