Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java의 다른 try catch 블록 내에서 try catch 블록을 선언할 수 있습니까?

<시간/>

, 우리는 다른 try-catch 블록 내의 try-catch 블록을 중첩된 try-catch 블록이라고 합니다.

중첩된 Try-Catch 블록

  • 내부 시도 진술자 일치하는 catch 문이 없습니다. 특정 예외의 경우 컨트롤이 다음 try 문 catch 핸들러로 전송됩니다. 일치하는 catch 문에 대해 예상되는 것입니다.
  • catch 문 중 하나가 성공할 때까지 계속됩니다. , 또는 모든 중첩 시도까지 진술이 완료되었습니다.
  • 일치하는 catch 문이 없으면 자바 런타임 시스템 예외를 처리합니다.
  • 중첩된 try 블록일 때 내부 try 블록이 사용됩니다. 먼저 실행됩니다. 내부 try 블록에서 발생한 모든 예외는 해당 catch 블록에서 포착됩니다. 일치하는 catch 블록이 없으면 외부 try 블록의 catch 블록 모든 중첩된 try 문이 소진될 때까지 검사됩니다. 일치하는 블록이 없으면 Java Runtime Environment 실행을 처리합니다.

구문

try {
   statement 1;
   statement 2;
   try {
      statement 1;
      statement 2;
   }
   catch(Exception e) {
      // catch the corresponding exception  
   }  
}
catch(Exception e) {
   // catch the corresponding exception
}
   .............

예시

import java.io.*;
public class NestedTryCatchTest {
   public static void main (String args[]) throws IOException {
    int n = 10, result = 0;
      try { // outer try block
         FileInputStream fis = null;
         fis = new FileInputStream (new File (args[0]));
         try { // inner trty block
            result = n/0;
            System.out.println("The result is"+result);
         }  
         catch(ArithmeticException e) { // inner catch block
            System.out.println("Division by Zero");
         }
      }
      catch (FileNotFoundException e) { // outer catch block
         System.out.println("File was not found");
      }
      catch(ArrayIndexOutOfBoundsException e) { // outer catch block
         System.out.println("Array Index Out Of Bounds Exception occured ");
      }
      catch(Exception e) { // outer catch block
         System.out.println("Exception occured"+e);
      }
   }
}

출력

Array Index Out Of Bounds Exception occured