예외 처리문

조치에 예외를 처리하는 명령문을 추가할 수 있습니다.

IRL은 예외를 보고하고 처리하는 메커니즘을 제공합니다. 오류가 발생하면 규칙이 예외를 처리합니다. 이는 규칙의 정상 플로우가 인터럽트되고 규칙 엔진이 예외 핸들러 즉, 특정 유형의 오류를 처리하는 코드 블록을 찾으려 하는 것을 의미합니다. 예외 핸들러는 일반적으로 오류로부터 복구하는 데 필요한 조치를 수행합니다.

예외 설정

사용자가 예외를 발견하려면 코드의 한 파트에서 예외를 처리해야 합니다. 모든 Java™ 코드가 예외를 처리할 수 있습니다.

throw 표현식은 유형이 Java Throwable 유형 또는 서브클래스에 지정 가능한 모든 종류의 표현식입니다. API 또는 규칙에 throw 표현식을 지정할 수 있습니다. 예외가 발생하면 try-catch-finally 문 또는 IRL 코드가 실행되도록 하는 Java 코드를 사용하여 API 또는 규칙에서 예외를 발견할 수 있습니다.

참고:

처리된 예외는 throw 문으로 처리한 예외를 괄호로 묶어 표시하는 IlrRunTimeExceptionIlrUserRuntimeException 하위 유형입니다.

  • IlrSystemRuntimeExceptionDecision Server 가 런타임 시 오류를 발견할 때 발생합니다. 이러한 유형의 예외는 복구될 수 없습니다. 디버깅 용도로만 사용됩니다.

  • 한편으로는 IlrUserRuntimeException을 사용하여 컨텍스트를 재설정하고 규칙을 재실행할 수 있습니다.

try-catch-finally 문

try-catch-finally 문에 대해 다음과 같이 설명할 수 있습니다.

  • try 문은 예외가 처리되는 명령문의 블록을 식별합니다.

  • catch 문은 반드시 try 문과 연관되어야 하며 특정 유형의 예외를 처리할 수 있는 명령문의 블록을 식별합니다. try 블록 내에서 특정 유형의 예외가 발생하면 이 명령문이 실행됩니다. try 문 다음에 필요한 만큼 많은 명령문을 배치할 수 있습니다. 각 명령문은 괄호 안에 나열된 클래스, 해당 클래스의 서브클래스 또는 괄호 안에 나열된 인터페이스를 구현하는 클래스의 인스턴스인 모든 예외를 처리합니다.

  • finally 문은 try 문과 연관되어야 하고 try 블록에서 오류 발생 여부에 상관없이 실행되는 명령문 블록을 식별합니다. finally 문은 일반적으로 try 문의 코드 이후를 정리하는 데 사용됩니다. try 블록에서 예외가 발생하고 예외를 처리할 연관된 catch 블록이 있는 경우 제어가 처음에는 catch 블록으로, 그 다음에는 finally 블록으로 전송됩니다.

이러한 명령문의 일반적인 양식은 다음과 같습니다.

try {
    statements
} 
catch (ExceptionType1 name) {
    statements
} 
catch (ExceptionType2 name) {
    statements
} 
...
finally {
    statements
}

IRL을 통해 여러 유형의 예외를 처리하는 일반 예외 핸들러를 사용할 수 있습니다. 그러나 발생한 예외의 유형을 팔별하고 오류의 복구를 지원하기 위해 예외 핸들러를 한정하십시오. 너무 일반적인 핸들러를 사용하면 예상치 못한 예외 및 핸들러가 처리하도록 설계되어 있지 않은 예외를 발견하고 처리함으로써 코드에 오류가 발생하기 쉽습니다.

다음 try 문은 예외를 작성하고 이를 처리하는 방법을 예시합니다.

then {
   try {
      method1(1) ; 
      System.out.println("Call method1(1) was OK") ; 
   }
   catch ( Exception e ) { 
   System.out.println("Catch from method1(1) call") ; 
   }
   try {
      method1(2) ;
      System.out.println("Call method1(2) was OK") ;
   }
   catch ( Exception e ) { 
      System.out.println("Catch from method1(2) call") ; 
      System.out.println("Exception details :-") ;
      System.out.println("Message: " + e) ; 
   }
}

try-catch 문은 Java 클래스의 메소드 호출을 사용하여 method1 에 전달된 변수가 1와 같지 않을 때 예외를 처리합니다. 메소드1은 다음과 같습니다.

public static void method1(i) throws Exception{
   if (i == 1) { 
      System.out.println("method1 - Things are fine \n") ; 
   }
   else {        
      System.out.println("method1 - Somethings wrong! \n") ;
      throw new Exception("method1 - Its an exception! \n") ; 
   } 
}

규칙 엔진의 범위 내에서 임의의 규칙 또는 Java 코드에 의해 발생된 예외는 해당 특정 예외에 대한 try-catch 문에 의해 발견됩니다.

다음 CatchCustomer 규칙은 ILOG® 규칙 언어 및/또는 Java 코드에서 발생하는 예외를 포착할 수 있는 try-catch 문 블록의 예를 제공합니다. 규칙은 두 개의 클래스 ( CustomerItem) 와 Java Exception 클래스의 두 개의 서브클래스 ( TooHighExpenseIsNotMember) 를 사용합니다.

rule CatchCustomer
{
  when {
   ?c: Customer();
   ?item: Item();
  }
  then {
    try {  
      System.out.println("Customer " + ?c.getName() + " wants to buy "
                         + " item " + ?item.getLabel() + " for a price of " +
                         ?item.getPrice() + "$");
      IsMember(?c);
      ?c.buy(?item);
    }
    catch (TooHighExpense ex) {
      System.out.println("M/Mrs/Mz " + ?c.getName() + " you have already
                         bought:");
      int j = 0;
      for(j = 0; j<?c.getItems().size(); j++) {
        java.util.Enumeration ?i = ?c.getItem(j);
        System.out.println("   Item: " + ?i.getLabel() + " costs " +
                           ?i.getPrice() + "$");
      }
      System.out.println("You have at your disposal " + ?c.getBudget() + "$");
      System.out.println("The current purchase is not allowed");
    }
    catch (IsNotMember ex) {
      System.out.println("M/Mrs/Mz " + ?c.getName() + 
                         ", you are not a member; would you like to
                          subscribe?");
    }
  }
}

이 예제에서는, 고객에게 예산이 할당되어 있습니다. 고객은 할당된 예산을 초과하는 품목을 구입할 수 없습니다. 고객이 예산을 초과하는 품목을 구입하려 하면 TooHighExpense 예외가 처리됩니다. 또한 폼목을 구입하려면 고객이 회원이어야 합니다. 비회원이 품목을 구입하려 하는 경우 IsNotMember 예외가 처리됩니다.

CatchCustomer 규칙에서 사용되는 두 개의 Java 클래스 IsNotMemberTooHighExpense 는 다음과 같습니다.

public class IsNotMember extends Exception
{
    public IsNotMember(String name){
      super();
      this.customer = name;
    }
    public void printStackTrace(PrintWriter s){ 
      s.println("An IsNotMember exception has been caused by customer "
                + customer + ". We are sorry but you can not make a purchase "
                + "without being a member.");
      super.printStackTrace(s);
      }
    String customer;
};


public class TooHighExpense extends Exception
{
    public TooHighExpense(String name, int expense, int limit, int price){
      super();
      this.expense = expense;
      this.limit = limit;
      this.price = price;
      this.customer = name;
    }
    public void printStackTrace(PrintWriter s){ 
      s.println("A TooHighExpense exception has been caused by customer "
                + customer + ". For this customer, the current expense is " + expense + 
                " and the authorized budget is " + limit +
                ". The purchase of the item whose price is " + price
                + " is not allowed.");
      super.printStackTrace(s);
      }
    private int price;
    private int limit;
    private int expense;
    String customer;
};