BackEnd/Java

[Java]예외처리(Exception) try~catch문 예제

Hojung7 2024. 8. 12. 14:40

#예제1

package pkg2.service;

import java.util.Scanner;

public class TryCatchFinallyService {
private Scanner sc = new Scanner(System.in);
	
	/**
	 * finally 확인하기
	 */
	public void test1() {
		try {
			System.out.println("1. 정상 수행 / 2. 예외 강제 발생 : ");
			int input = sc.nextInt();
			
			if(input == 1) {
				System.out.println("예외 없이 정상 수행됨");
			}else {
				throw new Exception("강제로 던져진 Exception");
			}
				
		}catch(Exception e) {
			System.err.println( e.getMessage()   );
		}finally {
			System.out.println("===무조건 수행===");
		}
		}

 

#결과

#예제2

 public void test2() {
		 
		 // Scanner 이용 시 맨날 뜨던 노란줄
		 // -> Resource leak : 'scan' is never closed
		 //    scan이 참조하는 객체가 닫히지 않아서
		 //    자원(메모리)이 누수되고 있어
		 //  -> 키보드와 연결된 통로(Stream)가
		 //      닫히지 않고 남아있어서 메모리가 쓸데없이 소비됨
		 
		 Scanner scan = new Scanner(System.in);

			try {
				System.out.print("1. 정상 수행 / 2. 예외 강제 발생 : ");
				
				int input = scan.nextInt();
				
				if(input == 1) {
					System.out.println("예외 없이 정상 수행됨");
				
				} else {
					throw new Exception("강제로 던져진 Exception");
				}
				
			} catch(Exception e) {
				System.err.println( e.getMessage() );

			} finally {
				scan.close();
				System.out.println("==== scan close 완료====");
				// 예외 발생 여부 관계없이 무조건!!!
				// 외부 입력 장치와의 통로를 닫아서
				// 메모리를 반환 시켜주는 메서드
				// -> 프로그램 최적화 방법 중 하나
                                                                                                     	
				
			}
	 
		 
	 }

 

#결과