Exceptions: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 85: Line 85:
}
}


==[Java]==
==[[Java]]==
===Defining exceptions===
===Defining exceptions===
//Checked exception
//Checked exception
Line 120: Line 120:
//This code is always executed after exiting the try block
//This code is always executed after exiting the try block
}
}

==[[Python]]==
==[[Python]]==
[[Category:Python]]
[[Category:Python]]

Revision as of 17:39, 26 January 2007

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.

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
  }

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()