728x90

Exception (예외처리)


  - 사전에 프로그래머가 예상해서 처리 할 수 있는 가벼운 에러로 예외종류는 클래스 계층구조로 분리되어 있다.
  - 자바에서는 예상해서 처리 할 수 있는 예외상황에 대비하여 코드를 작성하게 함으로써  좀더 견고한 프로그램을
     만들도록 유도한다.

  CompileException - 고칠 수 없는 에러

      IOException
      FileNotFoundException
      ClassNotFoundException

  RunTimeException - 고칠 수 있는 에러

      ArrayIndexOutOfBoundException    ex)  for(int i=0; i<= ar.length ; i++) 
      NumberFormatException
      ArithmeticException

예외처리 방법

방법1 - 직접처리

try{

  처리내용

}catch(예외종류) { }
  catch(예외종류) { }
  catch(예외종류) { }
  finally{ }
-------------------------
 - finally절은 예외와 상관없이 수행된다 ( DB연동 해제시에 finally에서 한다.)
   심지어 앞에 return문이 있어도 finally절은 수행된다
   그러나 앞쪽에 System.exit(0)문이 있을때는 수행 하지 않는다.


class ExceptionTest
{
 public static void main(String args[])
 {
  try{
   int num = Integer.parseInt(args[0]);
    if(num%2 == 0)
    {
     System.out.println(num+"는 짝수 입니다.");
    }
    else
    {
     System.out.println(num+"은 홀수 입니다.");
    }
   
   }catch(ArrayIndexOutOfBoundsException e1)
   {
    System.out.println("배열 에러 :" +e1);
   }
   catch(NumberFormatException e2)
   {
    System.out.println("숫자 에러 :"+e2);
   }
   catch(ArithmeticException e3)
   {
    System.out.println("연산 :" + e3);
   } 
 }
}



방법2 - 간접처리

결과형 메서드(인수) throws 예외종류
{
      처리내용
}
  메서드가 호춛된 곳으로 제어권을 넘긴다. (main() 경우는 JVM에게 제어권을 넘긴다.)

class ExceptionTest_2
{
 public static void main(String args[]) throws Exception
 {
  int num = Integer.parseInt(args[0]);
  if(num%2 == 0)
  {
   System.out.println(num+"짝수입니다");
  }else
  {
   System.out.println(num+"홀수입니다");
  }
 }
}

방법3

  - throw
    새로운 Exception을 정의하고, throw문을 이용해서  새로 정의한 Exception을 발생시켜 사용

class ExceptionTest
{
    void method() throws MyException
       {
            if(MyException 발생조건)
                throw new MyException("메세지");  //예외생성
        }
}
class MyException extends Exception
{
   MyException(String msg)  //생성자 
        {  
              super(msg); //상위클래스(Exception) 호출
        }
}

class Jumsu
{
 public static double calcAvg(int jum[]) throws JumsuException
 {
  if(jum.length != 5)  //에러 발생 조건
  {
   throw new JumsuException("배열 에러...");
  }
  int sum = 0; // 합
  
  for(int i = 0 ; i < jum.length ; i++)
  {
   sum+= jum[i]; //합 구하기
  }
  return ((double)sum/jum.length);
 }//calcAvg
}
//////////////////////////////////////////////////////
class JumsuException extends Exception
{
 public JumsuException(String msg)
 {
  super(msg);
 }
}
//////////////////////////////////////////////////////
class ExceptionTest_4
{
 public static void main(String args[])
 {
  int myjum[]={66,77,88,99,55,11}; // 배열갯수를 변경하면 에러
  try{
   double avg = Jumsu.calcAvg(myjum);
   System.out.println("평균 :" +avg);
  }catch(JumsuException e)
  {
   System.out.println(e);
  }
 }
}

class ExceptionTest_5
{
 public static void main(String args[])
 {
  try{
   System.out.println("a()호출전");
   a();
   System.out.println("a()호출후");
  }catch(ArrayIndexOutOfBoundsException e)
   //{System.out.println("산술예외발생");}
  {e.printStackTrace();}//역추적
  finally{System.out.println("finally 메인블럭");}
 }
 public static void a()
 {
  try{
   System.out.println("b()호출전");
   b();
   System.out.println("b()호출후");
  }catch(ClassCastException e)
   //{System.out.println("형번환 예외 발생");}
  {e.printStackTrace();}
  finally{System.out.println("finally a 블럭 ");}
 }
 public static void b()
 {
  try{
   System.out.println("c()호출전");
   c();
   System.out.println("c()호출후");

  }catch(NumberFormatException e){

  //{System.out.println("수형식 예외 발생");}
  e.printStackTrace();}
  finally{System.out.println("finally b블럭");}
 }
 public static void c()
 {
  try{
   System.out.println("d()호출전");
   d();
   System.out.println("d()호출후");
  }catch(ArithmeticException e)
   //{System.out.println("산술연산 예외 발생");}
  {e.printStackTrace();}
  finally{System.out.println("finally c블럭");}
 }
 public static void d()
 {
  try{
   System.out.println("나누기전");
   int x = 1;
   int y = 0;
   System.out.println(x/y);  // 에러발생
  }catch(ArithmeticException e)
  {e.printStackTrace();}
  finally{System.out.println("finally d블럭");}
 }
}


+ Recent posts