..열심히 공부하세../JAVA 문법

[31] Exception 예외처리

댄스댄스 2012. 5. 4. 14:59

 

1. 오류의 구분 

   - 예외 (Exception) : 가벼운 오류이며 프로그램적으로 처리한다. 프로그래머가 해결할 수 있는 오류

 - 오류 (Error) : 치명적인 오류이며 JVM에 의존하여 처리한다. 프로그래머가 해결할 수 없는 오류

 

2. 예외처리(Exception handling) 에 대한 필요성

  - 프로그램의 비정상적인 종료를 막고, 정상적인 수행을 할 수 있도록 하기 위해서이다.

 

3. 예외의 구분

   - 일반적 예외 : 컴파일할 때 발생하는 오류이며,

                     컴파일할 때에 확인되므로 반드시 예외처리를 해야만 컴파일 된다.

- 실행 시 예외 : 배열의 범위를 넘었을때, 특정 수를 0으로 나누었을때등

                      프로그래머의 실수로 인한 예외이며,

                      예외처리를 하지 않아도 컴파일에는 무리가 없다.

 

4. 예외처리방법 

  ① try~catch문

     - 예상했던 예외가 발생하면 해당 예외 객체를 잡아(catch)내어 원하는 동작을 수행하고

       프로그램이 종료되지 않고 계속 진행할 수 있도록 하는 것.

 

  ② throws문

    - 예외를 처리하기보다는 발생한 예외객체를 양도하는 것.

    - 현재 메소드에서 예외처리를 하기가 조금 어려운 상태일때 현재 영역을 호출해준 곳으로

      발생한 예외객체를 대신 처리해 달라며 양도하는 것.

 

  ③ finally문

    - 예외가 발생하든 발생하지 않든 무조건 수행하는 부분.

 

5. try~catch문 형식

try{

//예외가 발생 가능한 문장들;

} catch(예상되는예외객체 변수명){

//해당 예외가 발생했을때 수행할 문장들;

}

 

6. 다중 catch문

try{

//예외가 발생 가능한 문장들;

} catch(예상되는예외객체1 변수명){

//해당 예외가 발생했을때 수행할 문장들;

} catch(예상되는예외객체2 변수명){

//해당 예외가 발생했을때 수행할 문장들;

} catch(예상되는예외객체3 변수명){

//해당 예외가 발생했을때 수행할 문장들;

}

 

7. finally문

try{

//예외가 발생 가능한 문장들;

} catch(예상되는예외객체1 변수명){

//해당 예외가 발생했을때 수행할 문장들;

} catch(예상되는예외객체2 변수명){

//해당 예외가 발생했을때 수행할 문장들;

} finally {

//예외발생 여부와 상관없이 수행할 문장들;

}

 

8. throws 예약어

접근제한 반환형 메소드명(인자1,…인자n) throws 예외클래스1,…예외클래스n {

 

}

 

==============================

 

-------------------------------------------------------Test12exception.java

package test3;

public class Test12exception {
 public static void main(String[] args) {
  
  //4.====================
  System.out.println(1);
  System.out.println(2);
  
  try{
   System.out.println(3);
   System.out.println(0/0);//예외발생
   System.out.println(4);

  }catch(ArithmeticException ae){
   System.out.println(5);
  }catch(Exception e){
   System.out.println("예외발생");
  }//반드시 맨 마지막에 와야 함.
  finally{
   System.out.println("나는 꼭 수행되어야 함.");
  }//예외발생여부와 상관없이 무조건 수행
  System.out.println(6);

  //3.=====================
  /*
  try{
   Exception e=new Exception("고의로 발생시킨 예외");
   System.out.println("예외객체 만들기만 함.");
   throw e;//예외를 발생시킴
   //throw new Exception("고의로 발생시킨 예외")
  }
  catch(Exception e){
   System.out.println("에러메시지:"+e.getMessage());
   e.printStackTrace();//문제가 발생한 정보를 모두 보여 줌
  }
  System.out.println("프로그램 정상 종료");
  */
  
  //2.===========================
  /*
  System.out.println(1);
  System.out.println(2);
  
  try{
   System.out.println(3);
   System.out.println(0/0);//예외발생
   System.out.println(4);

  }catch(Exception e){
   System.out.println(5);
  }
  System.out.println(6);
  //정상수행->5출력 안됨
  //예외발생->4출력 안되고 바로 catch문으로 이동
  *

  

//1.=======================
  /*
  int number=100;
  int result=0;
  //
  //for(int i=0;i<10;i++){
   //result=number/(int)(Math.random()*10);
   //System.out.println(result);
  //}
  
  //수정 소스
  for(int i=0;i<10;i++){
   try{
    result=number/(int)(Math.random()*10);
    System.out.println(result);
    System.out.println("정상수행");
   }catch (ArithmeticException e){
    System.out.println("0");
   }
  }
  //0으로 나누면 오류가 발생하므로 예외처리 해줌.
*/
 }

}

-------------------------------------------------ExceptionEx1.java

public class ExceptionEx1 {
    public static void main(String[] args) {
        // main()함수는 사용자가 호출하는 것이 아니라 JVM호출
  //실행이 값을 전달해 주면 main함수의 args변수가 받는다
  //args[0]  args[1]  args[2]
  //전달인자값의 구분은 space로 한다

        //ExceptionEx1 10 5
  //int a=int("123");//"123"
  int a=Integer.parseInt(args[0]); //5
  int b=Integer.parseInt(args[1]); //10
/*
        if (b == 0){
          System.out.println("0으로 나눌수 없습니다.");
          System.exit(1); // 프로그램 종료
        }
*/
        System.out.println(" a = " + a + " b = " + b );
        System.out.println(" a/b = " + (a/b) );
        System.out.println("나눗셈이 수행되었습니다.");
    }

}

-------------------------------------------------ExceptionEx2.java

public class ExceptionEx2 {
    public static void main(String[] args) {
  int a=Integer.parseInt(args[0]);
  int b=Integer.parseInt(args[1]);
  System.out.println(" a = " + a + " b = " + b );

        try{
     //만일 b값이 0일경우 예외발생
              System.out.println(" a/b=" + a/b );
  }
  catch(ArithmeticException e){
          // 예외 발생시 처리
          //System.out.println("[경고]예외발생:" + e.toString());
          //System.out.println("[경고]예외발생:" + e.getMessage());
          e.printStackTrace();
  }
  finally{
          // 무조건 실행
          System.out.println("나눗셈 연산이 종료 되었습니다.");
        }
     
      // 나머지 루틴 정상 실행
      System.out.println("나머지 루틴을 정상적으로 실행");

    }//main end

}//class end

 

-------------------------------------------------ExceptionEx3.java

package oop8ex;

public class ExceptionEx3 {
    public static void main(String[] args) {
        Integer integer = null;
        int i = 4;
/*
        if (i % 2 == 0){
            integer = new Integer(i);  //짝수일때만 객체 생성
        }

        if (integer == null){
            System.out.println("객체가 안 만들어 졌다.");
        }else{
            System.out.println("hashCode(): " + integer.hashCode());   
        }

        System.out.println("십진수: " + integer.intValue());
*/  
/*
NullPointerException [중요]
객체를 생성하지않고 메소드나 변수를 호출한 경우 NullPointerException 발생
이런 경우는 흔히 개발자의 판단 실수로 발생함으로 꼼꼼한 코드 테스트가 필요
*/   
        try
        {
            if (i % 2 == 0){
                integer = new Integer(i);  //짝수일때만 객체 생성
            }
           
            System.out.println("십진수: " + integer.intValue());
            System.out.println("2진수: " + integer.toBinaryString(i));
            System.out.println("8진수: " + integer.toOctalString(i));
            System.out.println("16진수: " + integer.toHexString(i));
        }
        catch(NullPointerException e)
        {
            System.out.println("객체를 만드세요.");
            System.out.println(e.toString());
        }
        finally
        {
            System.out.println("==================================");
            System.out.println("예외 처리 끝내고 finally 블럭을 수행한다");
        }
       
    }
}

 

-------------------------------------------------ExceptionEx4.java

package oop8ex;

public class ExceptionEx4 {
    public static void main(String[] args) {
 /*      
        try{
            Integer integer=null;
            //int n=integer.intValue();
           
            int a=10/0;
        }
        catch(NullPointerException e){
            System.out.println(e.toString());
        }
        catch(ArithmeticException e){
            System.out.println(e.toString());
        }
*/

/*
Exception 처리는 파생된 Exception를 상속해준
최고 조상에 해당하는 Exception클래스가 받아서 처리해 주는 형태를
많이 사용한다.
여러 예외가 있지만, 외우기 힘드므로 최고조상의 Exception만 사용해도 무방함.
*/
        try{
            Integer integer=null;
            int n=integer.intValue();
           
            int a=10/0;
        }
        catch(Exception e)
        {
            System.out.println(e.toString());
        }
       
    }

}

 

------------------------------------------------ThrowsEx.java

package oop8ex;

class Test1{
    public void print() throws Exception{
        int a = 10/0;//예외강제발생
        /*
        try
        {
            int a=10/0;
        }catch(Exception e){}
        */
    }

    public void disp() throws Exception{
        Integer integer=null;
        int n=integer.intValue(); //예외강제발생
        /*
        try
        {
            Integer integer=null;
            int n=integer.intValue();
        }catch(Exception e){}
        */
    }
}

public class ThrowsEx {
    public static void main(String[] args) {
        Test1 test=new Test1();
        try{
            test.print();//exception발생
            test.disp(); //exception발생
        }catch(Exception e){
            System.out.print(e.toString());
        }
       
    }
}