Exceptions: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Control Structures template)
No edit summary
Line 188: Line 188:
See http://perldoc.perl.org/perlvar.html#%24EVAL_ERROR for the meaning of the special variable <tt>$@</tt>. See http://search.cpan.org/dist/Error for an advanced, object based exception handling.
See http://perldoc.perl.org/perlvar.html#%24EVAL_ERROR for the meaning of the special variable <tt>$@</tt>. See http://search.cpan.org/dist/Error for an advanced, object based exception handling.

==[[PHP]]==
[[Category:PHP]]

'''Interpreter''': PHP 5.0+

Exceptions were not available prior to PHP 5.0
===Define exceptions===
class MyException extends Exception
{
// Custom exception attributes & methods
}

===Throwing exceptions===
function throwsException()
{
throw new Exception('Exception message');
}
===Catching Exceptions===
try {
throwsException();
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}


==[[Python]]==
==[[Python]]==

Revision as of 14:48, 17 February 2007

Control Structures

These are examples of control structures. You may also be interested in:

Task
Exceptions
You are encouraged to solve this task according to the task description, using any language you may know.

This task is to give an example of an exception handling routine and to "throw" a new exception.

Ada

Define an exception

 Foo_Error : Exception;

Raise an exception

 procedure Foo is
 begin
    raise Foo_Error;
 end Foo;

Handle an exception

 procedure Call_Foo is
 begin
    Foo;
 exception
    when Foo_Error =>
      -- do something
 end Call_Foo;

AppleScript

try

try
    set num to 1 / 0
    --do something that might throw an error
end try

try-on error

try
    set num to 1 / 0
    --do something that might throw an error
on error errMess number errNum
    --errMess and number errNum are optional
    display alert "Error # " & errNum & return & errMess
end try

throw

error "Error message." number 2000

C++

C++ has no finally construct. Instead you can do this in the destructor of an object on the stack, which will be called if an exception is thrown.

try-catch

 struct MyException
 {
   // data with info about exception
 };

 void foo()
 {
   throw MyException();
 }

 void call_foo()
 {
   try {
     foo();
   }
   catch (MyException &exc)
   {
     // handle exceptions of type MyException and derived
   }
   catch (...)
   {
     // handle any type of exception not handled by above catches
   }
 }

C#

Compiler: MSVS 2005

 public class MyException : Exception
 {
   // data with info about exception
 };

 void foo()
 {
   throw MyException();
 }

 void call_foo()
 {
   try {
     foo();
   }
   catch (MyException e)
   {
     // handle exceptions of type MyException and derived
   }
   catch
   {
     // handle any type of exception not handled by above catches
   }
 } 

Java

Defining exceptions

  //Checked exception
  public class MyException extends Exception {
     //Put specific info in here
  }
  //Unchecked exception
  public class MyRuntimeException extends RuntimeException {}

Throw exceptions

  public void fooChecked() throws MyException {
     throw new MyException();
  }
  public void fooUnchecked() {
     throw new MyRuntimeException();
  }

Catching exceptions

  try {
     fooChecked();
  }
  catch(MyException exc) {
     //Catch only your specified type of exception
  }
  catch(Exception exc) {
     //Catch any non-system error exception
  }
  catch(Throwable exc) {
     //Catch everything including system errors (not recommended)
  }
  finally {
     //This code is always executed after exiting the try block
  }

Standard ML

Define Exceptions

 exception MyException;
 exception MyDataException of int; (* can be any first-class type, not just int *)

Throw Exceptions

 fun f() = raise MyException;
 fun g() = raise MyDataException 22;

Catch Exceptions

 val x = f() handle MyException => 22;
 val y = f() handle MyDataException x => x;

JavaScript

Throwing exceptions

function doStuff() {
  throw new Error('Not implemented!');
}

Catching exceptions

try {
  element.attachEvent('onclick', doStuff);
}
catch(e if e instanceof TypeError) {
  element.addEventListener('click', doStuff, false);
}
finally {
  eventSetup = true;
}

Perl

# throw an exception
die "Danger, danger, Will Robinson!";

# catch an exception and show it
eval {
    die "this could go wrong mightily";
};
print $@ if $@;

# rethrow
die $@;

See http://perldoc.perl.org/perlvar.html#%24EVAL_ERROR for the meaning of the special variable $@. See http://search.cpan.org/dist/Error for an advanced, object based exception handling.

PHP

Interpreter: PHP 5.0+

Exceptions were not available prior to PHP 5.0

Define exceptions

class MyException extends Exception
{
    //  Custom exception attributes & methods
}

Throwing exceptions

function throwsException()
{
    throw new Exception('Exception message');
}

Catching Exceptions

try {
    throwsException();
} catch (Exception $e) {
    echo 'Caught exception: ' . $e->getMessage();
}

Python

try-except-finally-else

Interpreter: Python 2.5

Before Python 2.5 it was not possible to use finally and except together.

try:
   foo()
except TypeError:
   bar()
finally:
   baz()
else:
   # no exception occurred
   quux()