티스토리 뷰
생활코딩-java 수업을 듣고 중요 내용을 정리한 것입니다.
- 예제1
package Day20190720;
class Calculator{
int left, right;
public void setOprands(int left, int right) {
this.left = left;
this.right = right;
}
public void divide() {
try {
System.out.print("계산결과는 ");
System.out.print(this.left/this.right);
System.out.print("입니다.");
}catch(Exception e) {
System.out.println("오류가 발생했습니다. : ");
System.out.println("\n\ne.getMessage()\n"+ e.getMessage());
System.out.println("\n\ne.toString()\n"+e.toString());
System.out.println("\n\ne.printStackTrace()");
e.printStackTrace();
}
}
}
public class ExceptionEx1 {
public static void main(String[] args) {
Calculator c1 = new Calculator();
c1.setOprands(10, 0);
c1.divide();
}
}
<실행결과>
/ by zero
e.toString()
java.lang.ArithmeticException: / by zero
e.printStackTrace()
java.lang.ArithmeticException: / by zero
at Day20190720.Calculator.divide(ExceptionEx1.java:14)
at Day20190720.ExceptionEx1.main(ExceptionEx1.java:31)
- try...catch : 예외에서 핵심적인 역할을 담당하는 문법적인 요소
try{
예외의 발생이 예상되는 로직
}catch(예외클래스 인스턴스){
예외가 발생했을 때 실행되는 로직
}
try {
System.out.print("계산결과는 ");
System.out.print(this.left/this.right);
System.out.print("입니다.");
}catch(Exception e) {
System.out.println("오류가 발생했습니다. : ");
System.out.println("\n\ne.getMessage()\n"+ e.getMessage());
System.out.println("\n\ne.toString()\n"+e.toString());
System.out.println("\n\ne.printStackTrace()");
e.printStackTrace();
}
예외클래스 인스턴스 부분에 e는 변수이며 변수 앞의 Exception은 변수의 데이터 타입이다. Exception은 자바에서 기본적으로 제공하는 클래스로 java.lang에 소속되어 있다. 예외가 발생하면 자바는 마치 메소드를 호출하듯이 catch를 호출하면서 그 인자로 Exception 클래스의 인스턴스를 전달하는 것이다.
- e.getMessage(): 오류에 대한 기복적인 내용을 출력해준다. 상세하지 않다.
- e.toString(): e.getMessage()보다 더 자세한 예외 정보를 제공한다.
- e.printStackTrace(): 메소드 getMessage, toString과는 다르게 printStackTrace는 리턴값이 없다. 이 메소드를 호출
하면 메소드가 내부적으로 예외 결과를 화면에 출력한다. printStackTrace는 가장 자세한 예외
정보를 제공한다.
- 예제2 : 상황에 따라서 다른 예외가 발생할 수 있으므로 다중 catch를 보여줌.
package Day20190720;
class A{
private int[] arr = new int[3];
A() {
arr[0] = 0;
arr[1] = 10;
arr[2] = 20;
}
public void z(int first, int second) {
try {
System.out.println(arr[first] / arr[second]);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException");
}catch(ArithmeticException e) {
System.out.println("ArithmeticException");
}catch(Exception e) {
System.out.println("Exception");
}
}
}
public class ExceptionEx2 {
public static void main(String[] args) {
A a = new A();
a.z(10, 1);
a.z(1, 0);
}
}
<실행결과>
ArrayIndexOutOfBoundsException
ArithmeticException
- a.z(10, 1); 에서 arr배열에 인자가 10이 들어가게 되는데, 배열 arr은 3개의 값만을 담을 있기 때문에
존재하지 않는 인덱스의 값을 호출하고 있으므로 자바에서 ArrayIndexOutOfBoundsException을 발생시킨 것이다.
- a.z(1, 0); 에서 메소드z 내부적으로 10/0을 실행하게 되는데, 0으로 나누는 것은 불가능하기 때문에 자바는 ArithmeticException을 발생시킨다.
- 다중 catch를 보여주는 예제로 조건문의 else if처럼 여러 개의 catch를 하나의 try 구문에서 사용할 수 있다.
public void z(int first, int second) {
try {
System.out.println(arr[first] / arr[second]);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException");
}catch(ArithmeticException e) {
System.out.println("ArithmeticException");
}catch(Exception e) {
System.out.println("Exception");
}
}
메소드 z의 코드를 위와 같이 변경하면 컴파일 조차 되지 않을 것이다. 그것은 Exception이 ArrayIndexOutOfBoundsException, ArithmeticException 보다 포괄적인 예외를 의미하기 때문에 Exception 이후에 등장하는 catch문은 실행될 수 없는 구문이기 때문이다.
- finally : try구문에서 예외가 발생하는 것과 상관없이 언제나 실행되는 로직
try{
예외의 발생이 예상되는 로직
}catch(예외클래스 인스턴스){
예외가 발생했을 때 실행되는 로직
}finally{
예외 여부와 관계없이 실행되는 로직
}
예외와 상관없이 try 내의 구문이 실행되면 finally가 실행된다. 그럼 finally는 언제 사용하는 것일까?
(어떤 작업의 경우는 예외와는 상관없이 반드시 끝내줘야 하는 작업이 있을 수 있다. 예를 들어 데이터베이스를 사용한다면 데이터베이스 서버에 접속해야 한다. 이때 데이터베이스 서버와 여러분이 작성한 애플리케이션은 서로 접속상태를 유지하게 되는데 데이터베이스를 제어하는 과정에서 예외가 발생해서 더 이상 후속 작업을 수행하는 것이 불가능한 경우가 있을 수 있다. 예외가 발생했다고 데이터베이스 접속을 끊지 않으면 데이터베이스와 연결 상태를 유지하게 되고 급기야 데이터베이스는 더 이상 접속을 수용할 수 없는 상태에 빠질 수 있다. 접속을 끊는 작업은 예외 발생 여부와 상관없기 때문에 finally에서 처리하기에 좋은 작업이라고 할 수 있다. 말하자면 finally는 작업의 뒷정리를 담당한다고 볼 수 있다.
'Programming Language > Java' 카테고리의 다른 글
| 래퍼(wrapper) 클래스 (0) | 2019.07.23 |
|---|---|
| Object 클래스 (0) | 2019.07.22 |
| 예외처리(Exception Handling) - 만들기 (0) | 2019.07.21 |
| 예외처리(Exception Handling) - 예외 던지기 (0) | 2019.07.21 |