'예외처리(Exception)'에 해당되는 글 1건

  1. 2012.07.29 예외처리(Exception), try catch finally

* 예외 : 프로그래머가 원하지 않는 방향으로 가는 것.
* 오류 : 프로그램이 정상적으로 실행하지 못하는 상황.
  1. Error : 심각한 오류(프로그램을 멈춰야 하는 오류) - H/W적 오류
  2. Exception : mild오류(심각하지 않음 오류) - s/w적오류(실행시 정상적인흐름(programmer가 의도한 흐름)으로 가지 못한 상황.

* Exception Handling(예외처리)
- 예외가 발생되었을때 프로그램이 정상적으로 처리되도록 해주는 것.

Throwable - 오류의 최상위
^       ^
|       |
Error   Exception
           ^
           |
     ---------------
     |             |
   Runtime        나머지
   (unchecked)    (checked)

 

 

 


- Exception - unchecked 계열(Handleing(처리) : compiler가 신경쓰지 않음), checked 계열(compiler가 체크)
- unchecked : 컴파일러가 Exceoption 처리여부를 체크 않함
  발생이유 : code상의 문제 때문에 발생 (100퍼센트 실행 시 오류가 남. 코드를 수정해 주는 것이 맞음)
             compiler의 check가 불가능한 경우.
             -> 처리(Handling)보다는 code 수정

- checked 계열 Exception : 컴파일러가 Exception 처리여부를 check
                         하지 않았을 경우 컴파일 에러 발생
  발생이유 :  code상 문제가 아니라 user가 잘못 사용하였거나 실행 환경상 문제로 발생
  - 발생 확률 :  50 : 50
  -> 처리가 필요.

* 오류가 나면 그자리에서 처리 하는게 아니라 오류가 나는 곳의 상위에서 처리한다.
* throw, throws, try, catch, finally
throw :  오류를 발생시키는 것
throws, try, catch, finally : 오류를 처리하는 것.(try, catch, finally는 셋이 같이 붙어 다닌다. )
* Exception class 정의하는 법.

* Exception class 작성(교재 P537)
  1. checked :  Exception을 extends
     unchecked : RuntimeException을 extends
  2. public class
  3. no-arg 생성자
     String 인수로 받는 생성자
  4. 필요한 Attribute, 메소드를 구현.
     이름 ; ~Exception

* project : day24
  package : exception.sample
  class : ExceptionTest
          Divide
          ZeroDivideException

 


package exception.sample;

public class ExceptionTest {
 public static void main(String[] args){
 Divide d = new Divide();
 int result = 0;
 try{
  result = d.divide(10,0);
 }catch(ZeroDivideException ze){
      System.out.println("오류가 발생했습니다.");
      try {
   result = d.divide(10, 5);
  } catch (ZeroDivideException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 System.out.println("나눈 결과 : "+result);
 }
}

---------

 

package exception.sample;

public class Divide {
 
 public int divide(int num1, int num2) throws ZeroDivideException{
   //num1을 num2로 나눈 값(몫)을 return
  if(num2==0){ //예외상황
   throw new ZeroDivideException();
   
  }
  return num1/num2;
 }
}


-----------

package exception.sample;
/*
 * Exception 클래스
 * 0으로 숫자를 나눴을 때의 예외상황을 표현하기 위한 클래스
 */
public class ZeroDivideException extends Exception{
 public ZeroDivideException(){}
 public ZeroDivideException(String message){
  super(message);
 }
}


------------
==========================================================
* Exception 발생(던진다) - throw (호출해준 사람한테 예외를 던져준다.)
  구문 :  throw Throwable의 객체;

num2 = 0;

* 예외처리 : throws - 예외발생할 메소드를 호출한 caller메소드에서 처리하도록 하는 것.
             try,catch,finally - 발생한 예외를 직접처리하는 것.

 
- 메서드 구문 :  [제한자] return type 이름([매개변수들]) throws [ExceptionType, . . .]{}
ex :  public void go() throws AEception, BException{}


                 
* 메소드 overriding - 하위 class에서 부모의 메소드 재정의
        (instance 메소드)
- 규칙 - 전제; 이름동일
  1. return type, 매개변수가 동일
  2. 하위의 접근제한자가 상위 것과 같거나 더 넓어야한다.
* 3. 부모가 throws 한것만 할 수 있다.( exception )
     -> 부모에서 throws 한것 안 할 수 있다.


* Exception

     ^
     |
  --------
  |       |
AException BException
  |      
------
|    |
A1Exception A2Exception


Super

public void go() throws AE{}

Sub
public void go(){} ok
public void go() throws AE,BE{} no
public void go() throws A1E,A2E extends Super(){}  ok

- try, catch, finally - 오류처리

try{
 오류(예외)발생 가능성이 있는 코드 ->throw
                                          ->메소드 호출 -> throws

}catch(예외(오류) type 변수선언){
 처리코드;
}

* ex :
try{
 1.AE
 2.BE
 3.CE
}catch(AE a){
 4.
}catch(BE b){
 5.
}catch(CE c){
 6.
}
 7.

2. BE발생

1.->2.X->5.->7. //이렇게 이동. 만약 위에 것에 오류가 나면 아래 있는 것이 실행할 의미가 없으면 이렇게 하고, 아랫것도 실행해야 되면 try{}catch(){}를 따로 잡아줘야 한다.


*

project : day24
package : exception.trycatch
class : ExceptionTest1


package exception.trycatch;

public class ExceptionTest1 {
 public static void main(String[] args) {
  /*
   * uncheck 계열의 Exception
   * ArrayIndexOutOfBoundsException - 배열의 index 범위를 넘었을때 발생
   * NullPointerException - null값을 가진 변수의 instance멤버 호출시 발생
   * ArithmethicException - 산술 연산상 문제 발생시 발생(0으로 나눈 경우)
   */
  String str = null;
  try{
  System.out.println(str.concat("def"));//100%이므로 수정하는게 맞지만 연습용으로 try{}catch(){}를 쓴다.
  }catch(NullPointerException ne){
   System.out.println("NullPointerException 발생");
   
  }try{
  System.out.println(10/0);
  }catch(ArithmeticException ae){
   System.out.println("ArithmeticException 발생");
  }
  int[] arr = {10,20,30};
  try{
  System.out.println(arr[10]);
  }catch(ArrayIndexOutOfBoundsException arre){
   System.out.println("ArrayIndexOutOfBoundsException 발생");
  }
  System.out.println("메인메소드 종료");
 }
}


---------
============================================================================
*
package exception.trycatch;

public class ExceptionTest2 {
 public static void main(String[] args) {
  String str = null;
  try{
  str.concat("def");
  int result = 10/0;
  int arr[]= {10,20,30};
  System.out.println(arr[0]);
  
  int i = Integer.parseInt("abcde");
  }catch(NullPointerException e){
   System.out.println("NullPointerException발생");
  }catch(ArithmeticException ae){
   System.out.println("ArithmeticException발생");
  }catch(ArrayIndexOutOfBoundsException ae){
   System.out.println("ArrayIndexOutOfBoundsException발생");
  }catch(Exception e){ //모든 Exception의 상위 개념으로 위에서 잡은 것 말고는 다 여기서 잡는다.
   System.out.println("Exception e");
  }
  System.out.println("메인메소드 종료");
 }
 
}
----------------------
==========================================================================

--------------------
=============================================================================


 
* 2012-3-27

 오류                                                
          |
----------------------
|                     |
에러                 예외
심각한H/w적           S/W적

 

 Throwable
            |
--------------------------
|                         |
Error                    Exception
                          |
                   --------------------------
                   |                         |
     unchecked : RunTimeException   checked : exception(checked 는 사용자가 메뉴얼 대로 사용하지 않거나 호출이 잘못되었을 시 사용하는 exception이다.)

* 오버라이딩 규칙에 걸려서 exception을 던지지 못할 경우에는 Runtime계열의 Exception을 만들어 던진다.
ex : ABCException a = new ABCException();
     WrapperException we = new WrapperException(a);
     throw new we;

* exception은 잘못된 상황이 나오면 잘못된 상황을 표현하기 위한 class(exception)를 만들면된다.
  
* RuntimeException도 컴파일시 구문에 적어주지 않아도 에러가 나지 않지만 구문만 보고도 사용자가 Exception이 난다는 것을 알아야 하기 때문에 구문에 throws를 사용해서 나타내준다.
ex :

public void b() throws NullPointerException{

 throw new NullPointerException();
}

* 상속구조의 Exception을 잡을 시에는 하위 것부터 잡아야 한다. 왜냐하면 상위를 먼저 잡으면 상위에서 예외를 다 처리하여 하위 예외는 왜 썼냐고 물으면서 에러를 내기 때문이다.
* catch안에 아무것도 구현안해도 예외처리를 한것이기는 하나 로그를 남겨야 한다. (오류를 남겨 두지 않으면 프로그램이 아무 이상 없는 것으로 보이는데 프로그램이 실행이 안되는 경우가 생길 수 있다.)

* Exception 발생
public void addProduct()throws SameIDException{
  throw new SameIDException();
}
  메소드 호출
try{
pm.addProduct();
}catch(SameIDException se){
}


* 개발에서는 catch에 printStackTrace();를 한다.

*
try{
 예외가 날 확률이 있는 코드
}catch(  e){
 예외처리
}finally{
무조건 실행
}

----------------------------

try{ 1->4->5
1       - AE발생
2
3
}catch(AE e){
4
}
5

-----------------------------


try{
1     
2
3
}catch(AE e){
4
}finally{
5
}

예외가 없으면 1->2->3->5
1번에서 예외가 나면 1->4->5
1번에서 catch에서 잡지 않는 에러가 나면 1->5


----------------------------------
*IO
try{

 1.연결
 2.교환

}catch(){

 예외처리

}finally{

 3.연결끊기

}

----------------------------------
try : 오류날 가능성이 있는 코드-->실행코드(정상)
catch : try 블럭에서 난 오류를 처리하는 코드
finally : try와 catch의 상황과 상관 없이 무조건 실행되야 하는 코드.->실행코드(정상)

* 가능
- try{}catch(){}finally{}
- try{}finally{}
- try{}catch{}

 

 

'프로그래밍 > JAVA프로그래밍' 카테고리의 다른 글

File I/O filter처리  (0) 2012.07.29
File I/O  (0) 2012.07.29
난수구하기 및 수학함수  (0) 2012.07.29
java 시간 날짜 처리  (0) 2012.07.29
String class, String buffer  (0) 2012.07.29
Posted by 조은성
,