본문으로 바로가기
728x90
반응형
SMALL

예외처리란?

예외가 발생할 경우 프로그램이 할 일


 

*예외처리를 해야만 실행되는경우(CheckedException)

*예외처리를 하지 않아도 실행되는 경우(UncheckedException)

 

 

결국 try~catch, throws 의 근본적은 차이는 무엇일까?

예제를 보며 확인하자

TRY~CATCH 사용

package test;

public class test1 {
	public static void main(String[] args) {
		  int a=10;
		  int b=0;
		  int c=0;
		  try{
		    c=a/b;
		  }catch(NumberFormatException e){
		   System.out.println("catch2 실행");
		  }catch(ArithmeticException e){
		   b=1;
		   c=a/b;
		   System.out.println("catch1실행");
		   
		  }catch(Exception e){
		   System.out.println("catch3 실행");
		  
		  }
		  System.out.println("내가 출력 될까요?");
		  System.out.printf("%d/%d=%d\n",a,b,c);
		  System.out.println("main 끝!!");
		 }
		}
	

 

CATCH문을 실행하고

사용자는 프로그램을 종료할 수도 있고

계속 구문을 실행할 수도 있다.

결과

 

THROWS

package test;

public class test1 {
	public static void main(String[]args) throws Exception{
		  int a=10;
		  int b=0;
		  int c=0;
		  
		  c=a/b;
		  
		  System.out.println("내가 출력 될까요?");
		  //초기화 않된 지역변수 사용불가
		  System.out.printf("%d/%d=%d\n",a,b,c);
		  System.out.println("main 끝!!");
		 }
		}
	

 

결과

기본적인 예외를 해당 구문에 던져주어 책임을 전가하고

예외상황 처리가 수행된후 프로그램이 종료 된다

 

이 차이로서

예외상황 발생시

try~cath는 사용자가 흐름을 능동적으로 제어할 수 있고

throws는 강제종료 되기 때문에 수동적이다.

728x90
반응형
LIST