Exception을 만들어서도 쓴다.

Posted 2015. 4. 6. 13:44

package chap8;

// Exception 클래스를 상속 받아 MyException을 만들기

class MemoryException extends Exception{
 public MemoryException(){
  super("메모리가 부족합니다.");
 }
}

class SpaceException extends Exception{
 final int ERR_CODE;
 public SpaceException(){
  super("설치 공간이 부족합니다.");
  ERR_CODE = 100;
 }
 
 public int getErrCode(){
  return ERR_CODE;
 }
}

public class ExceptionEx8{
 boolean isSpace() { return false; }
 boolean isMemory() { return true; }
 public static void main( String[] args ){
  ExceptionEx8 m = new ExceptionEx8();
  try{
   if( !m.isMemory() )
    throw new MemoryException();
   if( !m.isSpace() )
    throw new SpaceException();
  } catch( MemoryException e ){
   System.out.println("메모리가 부족합니다.");
  } catch( SpaceException e ){
   System.out.println("저장 공간이 부족합니다.");
   System.out.println("ERR_CODE : " + e.ERR_CODE);
   e.printStackTrace();
  }
 }
}

 

'Java !!!' 카테고리의 다른 글

equals_2  (0) 2015.04.07
equals  (0) 2015.04.07
예외처리 Exception( 런타임과 컴파일 차이 )  (0) 2015.04.06
예외처리 Exception  (0) 2015.04.06
C++과 Java의 다른점  (0) 2015.04.05

package chap8;

public class ExceptionEx5 {
 public static void main(String[] args) {
  // RuntimeException는 컴파일 중 에러는 무시하고 런타임중 에러를 잡겠다는 것.
  // 걍 Exception은 컴파일 도중도 포함 된다.
  throw new RuntimeException("예외 고의로 발생2");
 }
}

 

'Java !!!' 카테고리의 다른 글

equals  (0) 2015.04.07
Exception을 만들어서도 쓴다.  (0) 2015.04.06
예외처리 Exception  (0) 2015.04.06
C++과 Java의 다른점  (0) 2015.04.05
동적할당 정적할당 개념  (0) 2015.04.04

예외처리 Exception

Posted 2015. 4. 6. 13:09

package chap8;

// throws : 예외처리
// tyr mehod1() -> method1()에서 method2 호출 -> method2에서 catch 실행
// -> catch에 throw가 있으면 호출한 곳으로 알림 -> method1에서 catch 호출
// -> method1을 호출한 곳의 catch 호출. 로 흘러간다.

public class ExceptionEx7 {
 public static void main(String[] args){
  try{
   method1();
  } catch( Exception e ){ // throw로 넘어 왔다면 catch 실행한다.
   System.out.println("main에서 예외처리");
  }
 }
 
 private static void method1() throws Exception {
  try{
   method2();
  } catch ( Exception e){
   System.out.println("method1에서 예외처리");
   throw e; // 2. 2에서 넘어온 에러 내용을 method1을 호출한 곳으로 간다.
  }
 }
 
 private static void method2() throws Exception {
  try{
   throw new Exception("thorws로 예외처리해야함");
  }catch ( Exception e ){
   System.out.println("method2에서 예외처리");
   throw e; // 1. 예외 재 발생 -> 호출한 곳으로 간다.
  }
 }
}

« PREV : 1 : ··· : 15 : 16 : 17 : 18 : 19 : 20 : 21 : ··· : 77 : NEXT »