logo

Java try-catch 블록

자바 시도 블록

자바 노력하다 블록은 예외를 발생시킬 수 있는 코드를 묶는 데 사용됩니다. 메서드 내에서 사용해야 합니다.

try 블록의 특정 문에서 예외가 발생하면 나머지 블록 코드는 실행되지 않습니다. 따라서 예외를 발생시키지 않는 try 블록에 코드를 보관하지 않는 것이 좋습니다.

Java try 블록 뒤에는 catch 또는 finally 블록이 와야 합니다.

Java try-catch 구문

 try{ //code that may throw an exception }catch(Exception_class_Name ref){} 

try-finally 블록의 구문

 try{ //code that may throw an exception }finally{} 

자바 캐치 블록

Java catch 블록은 매개변수 내에서 예외 유형을 선언하여 예외를 처리하는 데 사용됩니다. 선언된 예외는 상위 클래스 예외(예: Exception) 또는 생성된 예외 유형이어야 합니다. 그러나 좋은 접근 방식은 생성된 예외 유형을 선언하는 것입니다.

설정 메뉴 안드로이드

catch 블록은 try 블록 뒤에만 사용해야 합니다. 단일 try 블록으로 여러 catch 블록을 사용할 수 있습니다.

Java try-catch 블록의 내부 작업

Java try-catch 블록

JVM은 먼저 예외가 처리되었는지 여부를 확인합니다. 예외가 처리되지 않는 경우 JVM은 다음 작업을 수행하는 기본 예외 처리기를 제공합니다.

  • 예외 설명을 인쇄합니다.
  • 스택 추적(예외가 발생한 메소드의 계층 구조)을 인쇄합니다.
  • 프로그램이 종료됩니다.

그러나 애플리케이션 프로그래머가 예외를 처리하면 애플리케이션의 정상적인 흐름이 유지됩니다. 즉, 나머지 코드가 실행됩니다.

예외 처리가 없는 문제

try-catch 블록을 사용하지 않는 경우의 문제를 이해해 보겠습니다.

실시예 1

TryCatchExample1.java

 public class TryCatchExample1 { public static void main(String[] args) { int data=50/0; //may throw exception System.out.println('rest of the code'); } } 
지금 테스트해보세요

산출:

 Exception in thread 'main' java.lang.ArithmeticException: / by zero 

위의 예에 표시된 것처럼 나머지 코드 실행되지 않습니다(이 경우 나머지 코드 명세서는 인쇄되지 않습니다).

예외 뒤에 100줄의 코드가 있을 수 있습니다. 예외가 처리되지 않으면 예외 아래의 모든 코드가 실행되지 않습니다.

예외 처리를 통한 솔루션

Java try-catch 블록을 통해 위 문제의 해결 방법을 살펴보겠습니다.

실시예 2

TryCatchExample2.java

 public class TryCatchExample2 { public static void main(String[] args) { try { int data=50/0; //may throw exception } //handling the exception catch(ArithmeticException e) { System.out.println(e); } System.out.println('rest of the code'); } } 
지금 테스트해보세요

산출:

 java.lang.ArithmeticException: / by zero rest of the code 

위의 예에 표시된 것처럼 나머지 코드 실행됩니다. 즉, 나머지 코드 명세서가 인쇄됩니다.

실시예 3

이 예에서는 예외를 발생시키지 않는 try 블록에 코드를 보관했습니다.

TryCatchExample3.java

 public class TryCatchExample3 { public static void main(String[] args) { try { int data=50/0; //may throw exception // if exception occurs, the remaining statement will not exceute System.out.println('rest of the code'); } // handling the exception catch(ArithmeticException e) { System.out.println(e); } } } 
지금 테스트해보세요

산출:

 java.lang.ArithmeticException: / by zero 

여기서, try 블록에서 예외가 발생하면 나머지 블록 코드는 실행되지 않는 것을 알 수 있습니다.

실시예 4

여기서는 상위 클래스 예외를 사용하여 예외를 처리합니다.

삽입 파이썬

TryCatchExample4.java

 public class TryCatchExample4 { public static void main(String[] args) { try { int data=50/0; //may throw exception } // handling the exception by using Exception class catch(Exception e) { System.out.println(e); } System.out.println('rest of the code'); } } 
지금 테스트해보세요

산출:

 java.lang.ArithmeticException: / by zero rest of the code 

실시예 5

예외 발생 시 사용자 정의 메시지를 인쇄하는 예를 살펴보겠습니다.

TryCatchExample5.java

 public class TryCatchExample5 { public static void main(String[] args) { try { int data=50/0; //may throw exception } // handling the exception catch(Exception e) { // displaying the custom message System.out.println('Can't divided by zero'); } } } 
지금 테스트해보세요

산출:

 Can't divided by zero 

실시예 6

catch 블록에서 예외를 해결하는 예를 살펴보겠습니다.

TryCatchExample6.java

 public class TryCatchExample6 { public static void main(String[] args) { int i=50; int j=0; int data; try { data=i/j; //may throw exception } // handling the exception catch(Exception e) { // resolving the exception in catch block System.out.println(i/(j+2)); } } } 
지금 테스트해보세요

산출:

 25 

실시예 7

이 예에서는 try 블록과 함께 catch 블록에 예외 코드도 포함합니다.

TryCatchExample7.java

 public class TryCatchExample7 { public static void main(String[] args) { try { int data1=50/0; //may throw exception } // handling the exception catch(Exception e) { // generating the exception in catch block int data2=50/0; //may throw exception } System.out.println('rest of the code'); } } 
지금 테스트해보세요

산출:

 Exception in thread 'main' java.lang.ArithmeticException: / by zero 

여기서는 catch 블록에 예외 코드가 포함되어 있지 않음을 알 수 있습니다. 따라서 예외 코드를 try 블록 내에 포함하고 예외 처리에만 catch 블록을 사용하십시오.

실시예 8

이 예에서는 생성된 예외(산술 예외)를 다른 유형의 예외 클래스(ArrayIndexOutOfBoundsException)를 사용하여 처리합니다.

TryCatchExample8.java

 public class TryCatchExample8 { public static void main(String[] args) { try { int data=50/0; //may throw exception } // try to handle the ArithmeticException using ArrayIndexOutOfBoundsException catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println('rest of the code'); } } 
지금 테스트해보세요

산출:

 Exception in thread 'main' java.lang.ArithmeticException: / by zero 

실시예 9

확인되지 않은 또 다른 예외를 처리하는 예를 살펴보겠습니다.

TryCatchExample9.java

 public class TryCatchExample9 { public static void main(String[] args) { try { int arr[]= {1,3,5,7}; System.out.println(arr[10]); //may throw exception } // handling the array exception catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println('rest of the code'); } } 
지금 테스트해보세요

산출:

 java.lang.ArrayIndexOutOfBoundsException: 10 rest of the code 

실시예 10

확인된 예외를 처리하는 예를 살펴보겠습니다.

TryCatchExample10.java

 import java.io.FileNotFoundException; import java.io.PrintWriter; public class TryCatchExample10 { public static void main(String[] args) { PrintWriter pw; try { pw = new PrintWriter('jtp.txt'); //may throw exception pw.println('saved'); } // providing the checked exception handler catch (FileNotFoundException e) { System.out.println(e); } System.out.println('File saved successfully'); } } 
지금 테스트해보세요

산출:

배우 사이 팔라비
 File saved successfully