예외 처리 문법

위키백과, 우리 모두의 백과사전.

예외 처리 문법프로그래밍 언어 간에 다양하며 부분적으로는 시맨틱 차이를 두며 크게는 각 언어의 전반적인 문법 구조에 맞춘다. 일부 언어들은 관련 개념 예외 처리를 호출하지 않지만, 다른 언어들은 이를 위해 직접적인 기능은 없어도 구현을 위한 수단을 제공하기도 한다.

대체적으로 오류 처리는 try...[catch...][finally...] 블록을 사용하며 오류들은 throw 문을 통해 생성되지만 명명 규칙과 문법에 따른 상당한 다양성이 있다.

예외 처리 문법 카탈로그[편집]

Bash[편집]

#!/usr/bin/env bash
#set -e provides another error mechanism
print_error(){
	echo "there was an error"
}
trap print_error exit #list signals to trap
tempfile=`mktemp`
trap "rm $tempfile" exit
./other.sh || echo warning: other failed
echo oops)
echo never printed

다음과 같은 문법으로 신호에 응함으로써 여러 오류에 대한 트랩을 설정할 수 있다.

trap 'echo Error at line ${LINENO}' ERR

베이직[편집]

ON ERROR GOTO handler
OPEN "Somefile.txt" FOR INPUT AS #1
CLOSE #1
PRINT "File opened successfully"
END

handler:
PRINT "File does not exist"
END  ' RESUME may be used instead which returns control to original position.

C[편집]

#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>

enum { SOME_EXCEPTION = 1 } exception;
jmp_buf state;

int main(void)
{
  if(!setjmp(state))                      // try
  {
    if(/* something happened */)
    {
      exception = SOME_EXCEPTION;
      longjmp(state, 0);                  // throw SOME_EXCEPTION
    }
  } 
  else switch(exception)
  {             
    case SOME_EXCEPTION:                  // catch SOME_EXCEPTION
      puts("SOME_EXCEPTION caught");
      break;
    default:                              // catch ...
      puts("Some strange exception");
  }
  return EXIT_SUCCESS;
}

C++[편집]

#include <exception>
int main() {
   try {
       // do something (might throw an exception)
   }
   catch (const std::exception& e) {
        // handle exception e
   }
   catch (...) {
        // catches all exceptions, not already caught by a catch block before
        // can be used to catch exception of unknown or irrelevant type
   }
}

자바[편집]

try {
   // Normal execution path
   throw new EmptyStackException();
} catch (ExampleException ee) {
   //  deal with the ExampleException
} finally {
   // This optional section is executed upon termination of any of the try or catch blocks above, 
   //  except when System.exit() is called in "try" or "catch" blocks;
}

[편집]

my ( $error, $failed );
{
   local $@;
   $failed = not eval {
       # Code that could throw an exception (using 'die')
       open(FILE, $file) || die "Could not open file: $!";
       while (<FILE>) {
           process_line($_);
       }
       close(FILE) || die "Could not close $file: $!";
       return 1;
   };
   $error = $@;
}

if ( $failed ) {
   warn "got error: $error";
}

펄 5.005에 오브젝트 외 문자열까지 throw할 수 있는 기능이 추가되었다.

eval {
  open(FILE, $file) || die MyException::File->new($!);
  while (<FILE>) {
    process_line($_);
  }
  close(FILE) || die MyException::File->new($!);
};
if ($@) {
  # The exception object is in $@
  if ($@->isa('MyException::File')) {
    # Handle file exception
  } else {
    # Generic exception handling
    # or re-throw with 'die $@'
  }
}

파이썬[편집]

f = None
try:
   f = file("aFileName")
   f.write(could_make_error())
except IOError:
   print "Unable to open file"
except:   # catch all exceptions
   print "Unexpected error"
else:     # executed if no exceptions are raised
   print "File write completed successfully"
finally:  # clean-up actions, always executed
   if f:
      f.close()

같이 보기[편집]