我正在尝试绕过try / except块。我有带两个表的sqlite db,要在不同的数据框中加载。
存在三种可能的结果,表a或表b不在,或者都不存在。
我不清楚如何写try / except块?
例如
try:
df = pd.read_sql("select * from table_a", db)
try:
df2 = pd.read_sql("select * from table_b", db)
except DatabaseError:
print('no table b')
except DatabaseError:
print('no table a')
我该如何嵌套以说找不到表a或b?
答案 0 :(得分:3)
通过取消嵌套:)
public static void main(String[] args) {
// Moved scanner outside of the try-catch block so that it can be closed in the finally block.
Scanner input = new Scanner(System.in);
try {
long storage = 99999;
int choice;
int secondChoice;
boolean exit = true;
int i = 0;
System.out.println("Would you like to add a contact?" + " Type 1 for yes");
choice = input.nextInt();
// The TreeMap must go outside of the while loop, otherwise a new map is created each time.
TreeMap<String, List<String>> lastName = new TreeMap<String, List<String>>();
if (choice == 1) {
// Should this be "while (exit == false)" and you initialize exit above to be false?
while (exit == true) {
List<String> array = new ArrayList<String>();
System.out.println("Plese add first name");
array.add(input.next());
System.out.println("Plese add phone number");
array.add(input.next());
System.out.println("Plese add email address");
array.add(input.next());
System.out.println("Plese add last name");
String last = input.next();
lastName.put(last, array);
// The format of this output is perhaps not what you want.
System.out.println("This is what you just entered: " + lastName);
System.out.println("\nWould you like to add another contact?" + " Type 1 for yes - 2 for no");
secondChoice = input.nextInt();
if (secondChoice == 1) {
exit = true;
String hold = lastName.toString();
System.out.println(hold);
}
else {
// Using "Map.Entry. etc..." isn't what you want here, and also isn't type-specific.
for (Entry<String, List<String>> product : lastName.entrySet()) {
System.out.println(product.getKey() + " : " + product.getValue());
}
// You should have an exit condition for the loop here. Currently it continues infinitely.
// exit = false;
}
}
}
else {
System.out.println("Thank you for using my program");
}
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
input.close();
}
}
答案 1 :(得分:1)
您现有的代码可能是处理此问题的最佳方法。
但是,如果您要更改它以不区分这两个失败,则只需删除内部的try
:
try:
df = pd.read_sql("select * from table_a", db)
df2 = pd.read_sql("select * from table_b", db)
except DatabaseError:
print('either no table a, or no table b')
或者,如果您想同时检测到 个故障,只需依次执行以下操作:
df = df2 = None
try:
df = pd.read_sql("select * from table_a", db)
except DatabaseError:
pass
try:
df2 = pd.read_sql("select * from table_b", db)
except DatabaseError:
pass
if not df and not df2:
print('neither a nor b exists')
…,然后,如果需要也可以添加elif not df:
和elif not df2:
。