- exception handling syntax
- 예외 처리 구문
1 Bash[ | ]
Bash
Copy
#!/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
2 C[ | ]
C
Copy
#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;
}
3 C#[ | ]
C#
Copy
public static void Main()
{
try
{
// Code that could throw an exception
}
catch(System.Net.WebException ex)
{
// Process a WebException
}
catch(System.Exception)
{
// Process a System level CLR exception, that is not a System.Net.WebException,
// since the exception has not been given an identifier it cannot be referenced
}
catch
{
// Process a non-CLR exception
}
finally
{
// (optional) code that will *always* execute
}
}
4 C++[ | ]
C++
Copy
#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 catched by a catch block before
// can be used to catch exception of unknown or irrelevant type
}
}
5 Java[ | ]
Java
Copy
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;
}
6 JavaScript[ | ]
JavaScript
Copy
try {
// Statements in which exceptions might be thrown
throw 'error';
} catch(error) {
// Statements that execute in the event of an exception
} finally {
// Statements that execute afterward either way
}
7 PHP[ | ]
PHP
Copy
// Exception handling is only available in PHP versions 5 and greater.
try
{
// Code that might throw an exception
throw new Exception('Invalid URL.');
}
catch (FirstExceptionClass $exception)
{
// Code that handles this exception
}
catch (SecondExceptionClass $exception)
{
// you get the idea what i mean ;)
}
8 Python[ | ]
Python
Copy
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()