首先是任務:我必須列印出一個特定的字串,其中包括我自定義例外的動態和靜態型別。在 a 中try and catch,我必須用不同的方式表達該catch部分來做同樣的事情。
我對如何列印出靜態型別和動態型別有點困惑。我也可以一起作業嗎getClass()
所以只是為了更準確的解釋,這是我到目前為止的代碼:
String s1 = "1 : ";
String s2 = "Exception : ";
String s3 = "UpdateTimeBeforeLastUpdateException ";
String s4 = "UpdateTimeInTheFutureException ";
try {
outsourced(ts, cal, 1);
}
catch(UpdateTimeBeforeLastUpdateException exc1) {
System.out.println(s1 s2 s3 exc1);
}
catch(UpdateTimeInTheFutureException exc2) {
System.out.println(s1 s2 s4 exc2);
}
}
public void testCatch2(TimeStamp ts, Calendar cal, int test) throws Exception {
String s1 = "2 : ";
String s2 = "Exception : ";
String s3 = "UpdateTimeBeforeLastUpdateException ";
String s4 = "UpdateTimeInTheFutureException ";
try {
outsourced(ts, cal, 2);
}
catch(UpdateTimeBeforeLastUpdateException | UpdateTimeInTheFutureException exc) {
System.out.println();
}
}
private void outsourced(TimeStamp ts, Calendar cal, int n) throws Exception {
switch (n) {
case 1:
ts.updateWithExc1(cal);
break;
case 2:
ts.updateWithExc2(cal);
break;
case 3:
ts.updateWithExc3(cal);
break;
case 4:
ts.updateWithExc4(cal);
break;
case 5:
ts.updateWithExc5(cal);
break;
}
還有 3 種方法要來,但我的主要問題只是catch和outprint部分
uj5u.com熱心網友回復:
如果我的問題是正確的,我認為這可能會回答它:
try
{
… // do something that causes an exception
}
catch( final OneException | TwoException e )
{
if( e instanceof OneException e1 )
{
… // Handle OneException e1
}
else if( e instanceof TwoException e2 )
{
… // Handle TwoException e2
}
else throw new Error( "None of the expected exceptions caught" );
}
該instanceof語法需要更高版本的 Java(我猜是 14)。
使用 Java 17 版(并啟用預覽功能)應該可以使用如下switch陳述句:
try
{
… // do something that causes an exception
}
catch( final OneException | TwoException e )
{
switch( e )
{
case OneException e1 -> e1.printStackTrace(); // Handle OneException e1
case TwoException e2 -> System.out.println( e2.getMessage() ); // Handle TwoException e2
default -> { throw new Error( "None of the expected exceptions caught" ); }
}
}
坦白說,在第二個示例中,例外的處理很蹩腳……但它有效!
uj5u.com熱心網友回復:
您可以使用多捕獲陳述句。在 catch 塊中,您可以呼叫getClass().getName()例外物件。現在,您將擁有例外類的完全限定名稱。如果你只想要類名,而不是完全限定名,你可以使用String#split()并傳入一個點作為正則運算式 ( \Q.\E,如果你不用\Qand括起來\E,這意味著我們說的是匹配任何字符,而不是點)并從回傳的陣列中獲取最后一個元素。
你是這樣做的:我只是在重寫你的 testCatch2()
public void testCatch2(TimeStamp ts, Calendar cal, int test) throws Exception {
String s1 = "2 : ";
String s2 = "Exception : ";
try {
outsourced(ts, cal, 2);
} catch(UpdateTimeBeforeLastUpdateException | UpdateTimeInTheFutureException exc) {
System.out.println(s1 s2 exc.getClass().getName());
// If you don't want the fully qualified name, use the below statements.
// String[] parts = exc.getClass().getName().split("\\Q.\\E");
// System.out.println(s1 s2 parts[parts.length - 1]);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/406912.html
標籤:
