본문 바로가기

Archived(CSE Programming)/Java

Java_예외처리

# 예외처리

Soft한 에러 -> Exception

예외를 만났을 때, 처리를 하는 방법에 대해서만 이해하기

미리 다 예측해서 대응하기는 불가능하다

 

Object -> Throwable -> Exception, Error

Excetion 클래스는 다시 구분 Compile Exception / Runtime Exception

이러한 예외들을 대처하는 것이 예외처리

# TCF, TF

Try: 예외발생 코드

Catch: 예외 발생 후에 해야하는 작업들

Finally: 반드시 실행되는 코드(Finally 내부에 Try~Catch 쓸 수 있음)

(Try~Catch 외에 Try~Finally도 있음, Try~Finally는 throws 예외를 던질 때 사용)

> 계속 던지더라도 Catch를 통해서 결국에는 처리를 해야한다(Throws만 하는 것이랑 결과 달라질 수 있음)

다중 Exception으로 처리해주는 것이 좋다 (사용시점에서 처리해주는 것이 맞다)

 

제어의 흐름을 바꿔주는 작업들

다중 Catch를 잡을 때 Exception의 계층 구조(부모구문)에서부터 잡아줘야 한다

상속 잡을 때 Throwable 보다는 Exception으로 잡는 것이 보다 더 적절

 

// 일반적인 try~catch~finally
public class ExceptionMain {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String strAry [] = {"a", "b", "c"};
		try {
			// 의도적으로 <=를 통해 예외 발생
			for(int idx=0; idx <= strAry.length ; idx++) {
				System.out.println(strAry[idx]);
			}
		}catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("예외 발생 ~~");
			e.printStackTrace();
		}finally {
			System.out.println("always execution");
		}
		System.out.println("main end");
	}
}
// throws를 통해 예외 상위 클래스로 날리기
public class ExceptionMain {

	public static void main(String[] args) throws ArrayIndexOutOfBoundsException {
		// TODO Auto-generated method stub
		String strAry [] = {"a", "b", "c", "d"};
		// 의도적으로 <=를 통해 예외 발생
		for(int idx=0; idx <= strAry.length ; idx++) {
			System.out.println(strAry[idx]);
		}
		System.out.println("inner try");
		System.out.println("always execution");
		System.out.println("main end");
	}
}
// try~fianlly를 구성하면 throws 처리하더라도 finally로 처리가능
public class ExceptionMain {

	public static void main(String[] args) throws ArrayIndexOutOfBoundsException {
		// TODO Auto-generated method stub
		String strAry [] = {"a", "b", "c", "d"};
		// 의도적으로 <=를 통해 예외 발생
		try {
			for(int idx=0; idx <= strAry.length ; idx++) {
				System.out.println(strAry[idx]);
			}
		}finally {
			System.out.println("main end");
		}	
	}
}

만약 Throws를 통해 예외처리를 하더라도 Finally를 통해 처리를 해두는 것이 이상적!

cf. Java의 지역변수 선언과 동시에 초기화 필요!(하지 않으면 버전에 따라 다르긴하지만 컴파일에러)

 

Compile Exception

package com.since.intern.excep;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.since.intern.excep.util.SincException;

public class ExceptionDemo {
	public void compileE() throws Exception{
		// 자바 지역변수는 선언과 동시에 초기화 필요
		InputStreamReader isr = null;
		BufferedReader br = null;
		
		// 다형성 InputStreamReader 객체가 상속한 Reader 넘겨주기
		isr = new InputStreamReader(System.in);
		br = new BufferedReader(isr);
		
		// readLine 자체에서 throws를 통해 IOException 넘기고 있음
		String msg = br.readLine();
		System.out.println(msg);
	}
}
import com.since.intern.excep.ExceptionDemo;

public class ExceptionMain {

	public static void main(String[] args) {
		// 컴파일 예외
		try {
			ExceptionDemo demo = new ExceptionDemo();
			demo.compileE();
		}catch(Exception e) {
			e.printStackTrace();
		}
		System.out.println("main end");
	}
}

Runtime Exception

package com.since.intern.excep;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.since.intern.excep.util.SincException;

public class ExceptionDemo {
	// Compile Exception 알아보기
	...
	
	// 1이 아니면 의도적으로 예외 발생시키는 메서드
	public boolean a(int flag) throws SincException{
		System.out.println("before a");
		try {
			if(flag == 1) {
				System.out.println("success");
				return true;
			}
			else {
				try{
					throw new SincException("sinc exception execution");
				}
				finally {
					return false;
				}
			}
		}finally {
			System.out.println("after a");
		}
	}
}
import com.since.intern.excep.ExceptionDemo;

public class ExceptionMain {

	public static void main(String[] args) {
		// 런타임 예외
		try {
			ExceptionDemo demo = new ExceptionDemo();
			demo.a(2);
		}catch(Exception e) {
			e.printStackTrace();
		}
		System.out.println("main end");
	}
}

 

'Archived(CSE Programming) > Java' 카테고리의 다른 글

Java_Stream  (0) 2020.01.17
Java_Thread  (0) 2020.01.17
Java_다형성과 컬렉션  (0) 2020.01.16
Java_OOP와 다형성  (0) 2020.01.14
Java_자바의 기본  (0) 2020.01.13