Exceptions: Difference between revisions

Content added Content deleted
No edit summary
Line 57: Line 57:
{
{
switch (setjmp(env)) {
switch (setjmp(env)) {
case 0: /* try */
case 0: /* try */
foo();
foo();
break;
break;
case MY_EXCEPTION: /* catch MY_EXCEPTION */
case MY_EXCEPTION: /* catch MY_EXCEPTION */
/* handle exceptions of type MY_EXCEPTION */
/* handle exceptions of type MY_EXCEPTION */
break;
break;
Line 73: Line 73:
if an exception is thrown.
if an exception is thrown.


The exception can be of any type, this includes int's, other primitives, as well as objects.
===try-catch===


===Defining exceptions===
struct MyException
struct MyException
{
{
// data with info about exception
// data with info about exception
};
};

===Throw exceptions===
// this function can throw any type of exception
void foo()
void foo()
{
{
throw MyException();
throw MyException();
}
}

// this function can only throw the types of exceptions that are listed
void call_foo()
void foo2() throw(MyException)
{
{
try {
throw MyException();
}
foo();

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


Line 103: Line 110:
'''Compiler''': MSVS 2005
'''Compiler''': MSVS 2005


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

===Throw exceptions===
void foo()
void foo()
{
{
throw MyException();
throw MyException();
}
}

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

}
catch
{
// handle any type of exception not handled by above catches
}
}
=={{header|Factor}}==
=={{header|Factor}}==
===Throw Exceptions===
===Throw Exceptions===
Line 176: Line 184:


=={{header|Java}}==
=={{header|Java}}==
An exception needs to extend the Exception type.

===Defining exceptions===
===Defining exceptions===
//Checked exception
//Checked exception