Friday, July 27, 2007

Exception-Handling Fundamentals in JAVA , PYTHON, C

An exception is an abnormal condition that arises in a code sequence in run time. In other words, exception is a run time error. In computer languages that do not support exception handling,errors must be checked and handled manually.
* JAVA
Java Exception handling is managed via five keywords: try, catch,throw, throws, and finally.All exception types are subclasses of the built-in class Throwable. Immediately below Throwable are two subclasses that partition exception in to distinct branches. One branch is headed by Exception. This class is used for exceptional conditions that user program should catch.There is important subclass of Exception, called RuntimeException.The other branch is topped by Error.

This small program includes an expression that intentionally causes a divide-by-zero error.


NOTE: intentation gone when i published the post

class Exc0{
public static void main(String args[]) {


int d = 0;
int a = 42 / d;
}
}

When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred.

javac file.java
java Exc0

output:
java.lang.ArithmeticException: /by zero
at Exc0.main(Exc0.java:4)

* How to use try and catch

class Exc2 {

public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 32 / d;
System.out.println("This will not displayed");
}catch (ArithmeticException e){
System.out.println("Division by zero error");
}
System.out.println("code execution continues");
}
}

To guard against and handle in a run time error, simply enclose the code that you want to monitor in a try block.

This program generates the following ouput:

Division by zero error
code execution continues

Notice that the call to println() inside the try block is never executed.Once an exception is thrown, the program control transfers out of the try block into the catch block. Simply passing the exception as an argument to println() ,we can print the description of error . Add this peice of code -
System.out.println("Exception" + e); in catch clause.

throw
So far, we have been catching exceptions that are thrown by the java run time system. However, it possible for our program to throw an exception explicitly, using throw statement.

Class ThrowDemo {
static void demoproc( ) {
try {
throw new NullPointerException(“demo”);
}catch( NullPointerException e) {
System.out.println(“Caught inside demoproc”);
throw e;
}
}

public static void main(String args[]) {

try{
demoproc( );
}catch (NullPointerException e) {
System.out.println(“Recaught; “ + e);
}
}
}

This program gets two chances to deal with the same error. First, main() sets up an exception context and calls demoproc ( ). The demoproc( ) method then sets up another exception handling context and immediatelythrows a new instance of NullPointerException, which is caught on the next line . The exception is then rethrown.

Caught inside the demoproc
Recaught: java.lang.NullPointerException: demo

throw new NullpointerException( “demo”);

Here new is used to construct an instance of NullPointerException.


PYTHON

def fun1()
a = 2 / 0;
return a
try:
b = fun1( )
print b
print ‘hello’
except:
print ‘error’

NOTE: intentation gone when i published the post

Here we intentionally makes a divide by zero error. In python language , since the code is placed in try block, the control goes to except clause and print error. It will not print hello.


C – language

include the header file setjmp.h

jmp_buf env;

fun1(){
//longjmp(env,2);

printf(“hello”);
fun2();
}

fun2(){
/*normally this code will do something useful and longjmp on failure */



longjmp(env,3);
printf(“world”);
}

main(){
switch(setjmp(env)){
case 0: fun1();
break;
case 2: printf(“jumping from fun1”);
break;
case 3: printf(“jumping from fun2”);
break;
}
}

int setjmp(jmp_buf env)
Sets up the local jmp_buf buffer and initializes it for the jump. This macro saves the program's calling environment in the environment buffer specified by the env argument for later use by longjmp.

void longjmp(jmp_buf env, int value)
Restores the context of the environment buffer env that was saved by invocation of the setjmp macro in the same invocation of the program. After longjmp is completed, program execution continues as if the corresponding invocation of setjmp had just returned. If the value passed to longjmp is 0, setjmp will behave as if it had returned 1; otherwise, it will behave as if it had returned value

In the above C code , setjmp is called in the main program.fun1 calls the fun2 and in fun2, longjmp is called with value as 3.So control of program will go to setjmp which returns 3. It will execute the case 3 in the switch statement and prints out “jumping from fun2” as in the screen

referance from wiki pedia, is quite helping one http://en.wikipedia.org/wiki/Longjmp

No comments: