ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 예외처리
    Java 2023. 2. 19. 12:25
    학습목표

    예외처리 개념 이해 (error, exception 구분하기)
    런타임 시점, 컴파일 시점 예외에 이해
    try-catch 구문 이해
    finally 구문 이해
    throw 이해와 활용

     

    프로그램에서의 오류

     

    컴파일 오류 (compile error)

    프로그램 코드 작성 중 발생하는 문법적 오류

     

    실행오류

    실행 중인 프로그램이 의도하지않은 동작을 하거나 프로그램이 중지 되는 오류

     

    오류와 예외 클래스

     

    시스템 오류 (Error)

    가상 머신에서 발생, 프로그래머가 처리 할 수 없는 오류 (스택 메모리 오버플로우등등)

     

    예외(Exception)

    프로그램에서 제어 할수 있는 오류

    읽어들이려는 파일이 존재하지 않거나, 네트웍이나 DB연결이 안되는 경우

    자바는 안정성이 중요한 언어로 대부분 프로그램에서 발생하는 오류에 대해 문법적으로 예외 처리를 해야함

     

     

     

     

    예외(Exception)는 프로그램에서 제어 할수 있는 오류라고 하였다.

     

    그러면 어떻게 제어할까?

     

    try-catch 구문을 써보자

    try{
    예외가 발생할 수 있는 코드 부분
    }catch(처리할 예외 타입e){
    try 블록 안에서 예외가 발생했을때 예외를 처리하는 부분
    }

     

    배열의 오류를 처리하는 예제

    package ch08;
    
    public class ArrayExceptionHandling {
    
    	public static void main(String[] args) {
    
    		// 배열 선언과 동시에 초기화 하기
    //		int[] arr  = new int[10];	
    		int[] arr = { 1, 2, 3, 4, 5 }; // 배열의 길이 5 ,index - 4
    
    //		for (int i = 0; i < 10; i++) {
    //			System.out.println(arr[i]);
    //		}       //예외인지 검증단계를 거치지 않고 해서 예외가 뜸
    
    		try {
    			for (int i = 0; i < 10; i++) {
    				System.out.println(arr[i]);
    			}
    		} catch (ArrayIndexOutOfBoundsException e) { // Exception 최상위 예외 클래스 : 왠만한 예외는 확인이 된다.
    			System.out.println("개발자야 인덱스 길이 모르니!!");
    		}
    		System.out.println("비정상 종료되지 않았습니다.");
    
    	} // end of main
    } // end of class
    출력값
    
    1
    2
    3
    4
    5
    개발자야 인덱스 길이 모르니!!
    비정상 종료되지 않았습니다.
    검증 단계를 걸치고 인덱스 길이보다 길때 예외가 처리되는 부분을 확인 할 수 있다.

     

    그렇다면 예외발생 여부와 상관없이 내가 프로그램을 실행하거나 종료하고 싶으면 어떻게 하나?

     

    이번에도 소스코드를 보면서 이해해보자

     

    package ch08;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    
    public class Exception2 {
    
    	public static void main(String[] args) {
    
    		FileInputStream fis;
    		
    		try {
    			fis = new FileInputStream("a.txt");
    		} catch (FileNotFoundException e) {
    			System.out.println(e);
    			//return; 
    			//심지어 리턴문이 있어도 finally가 실행됩니다.
    		}catch (Exception e) {
    			System.out.println(e.toString());
    		}finally {
    			//try 문이 실행되면 반드시 실행 됨.
    			System.out.println("여기도 실행되나요?");
    		}
    	}
    
    }
    출력값
    
    java.io.FileNotFoundException: a.txt (지정된 파일을 찾을 수 없습니다)
    여기도 실행되나요?

     

    여기에서 return을 선언했을때도 예외처리가 발생하는 여부를 떠나 무조건 finally가 실행되는것을 볼 수 있다.
    어떤 작업의 경우는 예외와는 상관없이 반드시 끝내줘야 하는 작업이 있을 수 있다. 그래서 예외처리가 발생했는지 여부를 떠나 finally를 사용해 어떠한 작업을 끝맺음 할때 많이 사용한다.

     

    여기서 더 생각해보자면 메소드를 여러곳에 쓸때 그때마다 예외처리 여부와 상관없이 fianlly 구문을 넣어야 할까?

     

    finally문도 예외처리 여부와 상관없이 실행이 되지만 throw는 좀더 상위쪽으로 미루어 처리를 한다.

    메소드를 여러곳에서 쓰려고 할때 메소드에서 예외가 발생하고 예외처리를 할려고 하니 예외처리를 하기위해 수많은 try catch finally 구문을 넣어야 한다. 이러한 과정을 줄여주는것이 throw 구문이다.

     

     

     

    throws 개념에 이해

     

    package ch08;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    
    public class FileExceptionHandling2 {
    
    	public static void main(String[] args) {
    		MyFile file = new MyFile();
    		try {
    			file.inputData("하이~");
    		} catch (FileNotFoundException e) {
    			System.out.println("파일이 없네요.");
    		}
    	}
    }
    
    class MyFile {
    
    	// throws 던지다
    	// 누군가가 MyFile 클래스를 사용할 때
    	// inputData 오류가 날 수 있으니 예외 처리 흐름은 사용하는 사람이
    	// 알아서 구현 해 !!
    	public void inputData(String str) throws FileNotFoundException {
    		FileInputStream fis;
    		fis = new FileInputStream("test1.txt");
    	}
    
    }
    출력값
    
    파일이 없네요.

     

    예외 처리 사용과 활용

     

    package ch08;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Properties;
    
    public class MyException {
    
    	public static void main(String[] args) {
    		
    		TxtFileInputManager inputManager 
    		= new TxtFileInputManager("test.txt");
    		
    		try {
    			
    		String result = 	inputManager.readTxtfileDate();
    		System.out.println("result : " + result);
    		} catch (IOException e) { //Exception이랑 바꿔도 똑같다.
    			e.printStackTrace();
    		}
    	} //end of main
    }	//end of class
    
    class TxtFileInputManager{
    	
    	// 외부 파일을 내 메모리 상으로 가져올 수 있는 녀석
    	private FileInputStream fis;
    	private String fileName; //한글로 하면 한글이 깨지고 영어는 안깨짐
    	
    	public TxtFileInputManager(String fileName) {
    		this.fileName = fileName;
    	}
    	
    	public String readTxtfileDate() throws IOException {
    		//IOException 부모
    		//FileNotFoundException
    		fis = new FileInputStream(fileName);
    		Properties prop = new Properties();
    		prop.load(fis);
    		// KEY = VALUE <- 데이터를 읽어주는 녀석
    		// name = 홍길동 -> 홍길동 -> 추출
    		String name = prop.getProperty("name");
    		return name;
    	}
    }
    
    	class MyABEception extends IOException{
    		//사용자 정의 예외 클래스도 만들 수 있다.
    	}
    출력값
    
    result : MIKE

     

    'Java' 카테고리의 다른 글

    쓰레드(Thread)  (0) 2023.02.19
    제네릭  (0) 2023.02.19
    Object  (0) 2023.02.18
    인터페이스 활용 예제  (0) 2023.02.18
    인터페이스  (0) 2023.02.18
Designed by Tistory.