Javaでtry、catch、finallyブロックの間にステートメントを記述できますか?
いいえ、 try、catch、finallyブロックの間にステートメントを書き込むことはできません これらのブロックは1つのユニットを形成します。 試してみるの機能 キーワードは、例外オブジェクトを識別してその例外オブジェクトをキャッチし、識別された例外オブジェクトとともにコントロールをcatchブロックに転送することです。 tryブロックの実行を一時停止する 。 キャッチブロックの機能 tryによって送信された例外クラスオブジェクトを受信することです およびキャッチ その例外クラスオブジェクトを作成し、その例外クラスオブジェクトを catchで定義された対応する例外クラスの参照に割り当てます。 ブロック 。 最後にブロック s 例外に関係なく強制的に実行されるブロックです。
try with catch blockのようなステートメントを書くことができます 、複数のキャッチブロックで試してください 、finallyブロックで試す そしてキャッチして試して、最後にブロックします これらの組み合わせの間にコードやステートメントを書くことはできません。これらのブロックの間にステートメントを配置しようとすると、コンパイル時エラーがスローされます。
構文
try
{
// Statements to be monitored for exceptions
}
// We can't keep any statements here
catch(Exception ex){
// Catching the exceptions here
}
// We can't keep any statements here
finally{
// finally block is optional and can only exist if try or try-catch block is there.
// This block is always executed whether exception is occurred in the try block or not
// and occurred exception is caught in the catch block or not.
// finally block is not executed only for System.exit() and if any Error occurred.
} 例
public class ExceptionHandlingTest {
public static void main(String[] args) {
System.out.println("We can keep any number of statements here");
try {
int i = 10/0; // This statement throws ArithmeticException
System.out.println("This statement will not be executed");
}
//We can't keep statements here
catch(ArithmeticException ex){
System.out.println("This block is executed immediately after an exception is thrown");
}
//We can't keep statements here
finally {
System.out.println("This block is always executed");
}
System.out.println("We can keep any number of statements here");
}
} 出力
We can keep any number of statements here This block is executed immediately after an exception is thrown This block is always executed We can keep any number of statements here
-
JavaScriptのtryステートメントとcatchステートメントを例を挙げて説明します。
tryステートメントを使用すると、コードのブロックを実行してエラーをテストできます。これらのエラーは、catchステートメントによってキャッチおよび処理されます。 以下は、JavaScriptのtryandcatchステートメントのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-wid
-
Pythonのステートメントを除いて、最後にtryを説明します。
Pythonでの例外処理では、tryステートメントとexceptステートメントを使用して、例外をキャッチして処理します。 try句内のコードは、ステートメントごとに実行されます。 例外が発生した場合、残りのtryブロックはスキップされ、except句が実行されます。 例 try: 'apple' + 6 except Exception: print "Cannot concatenate 'str' and 'int' objects" 出力 Cannot concatenate 'str' and '