블로그 이미지
하루, 글. 그림. 영상매체. 표현을 도와주는 기기들. 도전 중. 동화다아아
    동화다아아

    카테고리

    분류 전체보기 (176)
    잡담 (1)
    IT 기기-리뷰&뉴스 (7)
    리뷰 - 도서 (1)
    리뷰 - 영상 (0)
    리뷰 - 그림/음악 (1)
    내장형 하드웨어 (163)
    Total
    Today
    Yesterday
    - 자바는 프로그램 실행 중 예외나 오류가 발생할 경우 정상적인 실행과정과 분리하여 처리한다.
     → Exception 클래스, Error 클래스가 있으며 이는 Throwable 클래스의 서브 클래스이다.
     → Exception 클래스의 경우 파일의 끝을 지나서 읽기를 시도하거나, 배열의 색인이 범위를 넘은 경우 등이다.
      -> RuntimeException
      -> IOException
     → Error 클래스는 메모리 부족, 정의되지 않은 클래스 등을 말한다.

     - 예외 객체의 생성은 JAVA 가상머신이 생성한다.
    JAVA 가상머신  →  예외객체  →  throw  →  catch
     → 예외 객체는 예외를 처리하는 부분으로 던진다.(throw)
     → 예외를 처리하는 부분은 이 객체를 포함(catch)하여 적절하게 처리한다.

     - Error 클래스의 오류
     → IOException 클래스 예외는 반드시 프로그램내에서 처리되어야 한다.
     → 예외를 처리하지 않으면 컴파일 오류가 발생
     → 일단 throws로 마구잡이로 던진다.(IOException)

    - try문의 형식과 실행
     → try에서 에러가 발생하면 자동으로 catch()로 점프(해당하는 Exciption을 찾는다.)
     → catch(예외 클래스 이름 예외 변수)
     → finally는 try문의 실행이 끝나기 전에 반드시 처리된다.
    // 입력받은 두 수의 합을 구하는 프로그램
    import java.io.*;

    public class AddTwoNumber
    {
      public static void main(String[] args) throws IOException
      {
        int aNum = NumberClass.readInteger("Enter the first integer : ");
        int bNum = NumberClass.readInteger("\nEnter the second integer : ");
        System.out.println("The sum of two number is " + (aNum + bNum));
      }
    }
    class NumberClass
    {
      // NumberClass 객체 생성 없이 메소드가 호출되므로 static으로 설정
      public static int readInteger(String prompt)
      {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        int num = 0;
        boolean getANum = false;

        while(!getANum)
        {
          System.out.print(prompt);
          System.out.flush(); // 강제 출력
          try
          {
            num = Integer.parseInt(stdin.readLine());
            getANum = true;  
          }
          // 정수형이 아닌 입력으로 인한 에러가 들어온다면
          catch(NumberFormatException exp)
          {
            System.out.println("Not an Integer. Enter an Integer/");
          }
          // 키보드 입력으로 인한 에러가 들어온다면(포괄적)
          // if ~ else문처럼 순서에 따른 프로그램 실행이 달라질 수 있다.
          catch(IOException exp)
          {
            System.out.println("Problem in I/O. Execution terminated!!.");
            System.exit(0);
          }  // end of try      
        }  // end of while
        return num;
      }  // end of readInteger()
    }  // end of NumberClass

     → 실행결과


     → public static int readInteger (String prompt) 
       -> NumberClass 객체의 생성없이 메소드가 호출됨으로 static으로 설정되었다.  

     → try문 내에 두개의 catch 블럭이 정의되었다.  

     →  catch (NumberFormatException exp) 

       -> parseInt() 메소드가 인수로 받은 문자열을 정수로 변환시킬 때, 인수가 정수를 나타내는 문자열이 아니면 NumberFormat Exception 클래스의 예외가 발생 이를 처리하는 catch 블럭은 오류메세지를 출력하고 try문의 실행을 끝낸다.

       -> 프로그램의 제어는 while문의 처음으로 돌아간다.   

     → catch (IOException exp)

       -> readLine() 메소드가 키보드로부터 입력을 받는 도중에 문제가 발생하여 IOException 오류가 발사될 때 처리하는 catch 블럭이다.  catch 블럭에서 오류메세지를 출력하고 프로그램을 종료시킨다.


    - catch 예제
    // 0으로 나누는 수식에서 던지는 예외를 처리하는 프로그램
    class
     DivisionByZero1
    {
      public static void main(String[] args)
      {
        int aNum = 9;
        int bNum = 0;
        // try 블럭에서 던져진 예외는 ArithmeticException클래스에 속한다.
        // Exception 클래스는 ArithmeticException 예외를 포착하는
        // catch 블럭이 먼저 나와야 한다.
        try
        {
          // 9/0으로 나누었으므로 Arithmetic(산술)예외(Exception)
          System.out.println(aNum/bNum);
        } // 예외를 던진다.
        // 하위 클래스인 ArithmeticException 예외를 포착하는 Catch가 먼저 나와야 한다.
        // 순서가 바뀌면 오류 
        catch(ArithmeticException exp) // 산술예외
        {
          System.out.println("ArithmeticException caught.");
        }
        catch(Exception exp)
        {
          System.out.println("Exception  caught.");
        }
      }
    }

     → 실행결과


    - finally 예제
    // finally 블럭의 사용을 보여주는 프로그램

    import
     java.io.*;

    class AddTwoNumberWithFinally
    {
      public static void main(String[] args) throws IOException
      {
        int aNum = NumberClass.readInteger("Enter the first integer : ");
        int bNum = NumberClass.readInteger("Enter the second integer : ");
        System.out.println("The sum of two number is " + (aNum + bNum));
      }
    }
    class NumberClass
    {
      public static int readInteger(String prompt)
      {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        int num = 0;
        boolean getANum = false;

        while(!getANum)
        {
          try
          {
            System.out.println("** in tryblock");
            System.out.print(prompt);
            System.out.flush();
            num = Integer.parseInt(stdin.readLine());
            getANum = true;
            System.out.println("** out tryblock");
          }
          catch(NumberFormatException exp)
          {
            System.out.println("** catch block 1: Not an Integer. Enter an Integer.");
          }
          catch(IOException exp)
          {
            System.out.println("** catch block 2: Problem in I/O. Execution terminated!!");
            System.exit(0);
          }
          // finally 블럭은 반드시 실행된다.
          finally
          {
            System.out.println("** finally block\n");
          }  // end of try
        }  // end of while
        return num;
      }  // end of readInteger()
    }  // end of NumberClass

    → 실행 결과

     
     
    Posted by 동화다아아
    , |

    최근에 달린 댓글

    최근에 받은 트랙백

    글 보관함