본문 바로가기
카테고리 없음

[Java] 18. Exception , try catch - 예외 처리

by 슈퍼닷 2015. 2. 16.
반응형

Exception 이란 무엇일까? Exception의 뜻은 예외이다.

스크립트상에서 발생하는 예외적인 상황을 의미하는 것이다.

한번 예외에 대해 보자.

 

 

public class ExceptionTest {
public static void main(String args[])
{
int [] arr = new int[3];
for(int i=0 ; i < arr.length ; i++)
{
 arr[i] = i;
}
System.out.println(arr[4]);
}


}

 

이 스크립트를 실행하면 ArrayIndexOutOfBoundsException 이라는 예외가 발생된다.

배열의크기를 초과한 Index를 호출하려 하였기 때문이다.

이런 예외적인 상황이 발생하면 시스템이 중지될 수도 있다. 그러므로 예외가 발생하면 처리를 해주어야한다.

 

그때 쓰이는게 try catch 구문이다.

 

 

public class ExceptionTest {
public static void main(String args[])
{
int [] arr = new int[3];
for(int i=0 ; i < arr.length ; i++)
{
 arr[i] = i;
}
try
{
System.out.println(arr[4]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
}


 

try 부분이 예외가 발생할 수 있는 스크립트를 실행하는 부분이고 , catch는 예외가 발생하였을 경우 실행되는 구문이다.

ArrayIndexOutOfBoundsException 처럼 특정한 Exception 을 설정할 수도 있지만

범용적으로 Excepiton e 를 사용하여도 무관하다. 하지만 특정한 상황에 사용할때에는 특정한 Exception은 필수다.

 

그러면 사용자정의 Exception도 필요하지않을까? 우리는 만들 수 있다.

public class ExceptionTest {
public static void main(String args[])
{
draw d = new draw();
d.draws("triangle", 11, 11, 11);
}
}

class MyException extends Exception
{
 
 public MyException(String reason)
 {
  super(reason); // reason의 이유로 인한 Exception 발생
 }
}

class draw
{
 private void triangle(int a , int b , int c)throws MyException
 {
  System.out.println("삼각형을 생성하겠습니다.");
  if(a > 10 || b > 10 || c > 10)
  {
   throw new MyException("Length's maximum is 10.");
  }
 }
 
 public void draws(String type , int a , int b , int c)
 {
  if ( type == "triangle")
  {
   try{
    triangle(11,11,11);
   }catch(MyException e){
    System.out.println(e.getMessage());
   }
  }
 }
}

 

여기서 이해가 안갈만한 것은 throw와 throws 부분일 것이다.

throw는 위로 보내고 throws는 밑으로 보낸다고 생각하면된다.

throw는 메소드에 보내는것이고 throws는 메소드에서 밖으로 예외를 보내어 catch를 할수 있게하는것이다.

반응형

댓글