Sei sulla pagina 1di 12

EXCEPTION HANDLING

In our daily life we will be committing so many mistakes. Similarly in the process of developing a software a programmer will also perform many mistakes. In computer terminology those mistakes are called as BUGS or ERRORS. The process of removing these errors in known as DEBUGGING. Types of errors : 1. Compile-time errors 2. Run-time errors 3. Logical errors Compile-time errors : Consider the following code class demo { public static void main(String args[]) { System.out.println("this is my first java program") } } When we run this code it generates an error since semi-colon is missing after the statement : System.out.println("this is my first java program") Such errors are known as SYNTAX ERRORS and are caught when a program is compiled. These compile time errors are found by java compiler i.e., javac Logical errors : Consider the following code. It is written to calculate the salary of employee after getting 15% hike added to his basic salary. class demo { public static void main(String args[]) { double salary = 5000; salary = salary * (15/100); System.out.println("after incrementing salary = "+ salary); } } For the above program expected result is : 5750 that is :5000 + (5000 * (15/100)) = 5750

But when the above code is executed the output will be : 750 This is because : The statement that was written to calculate the salary is wrong. That is , it written as : salary = salary * (15/100); but it must be written as : salary = salary + (salary * (15/100)); such errors are not caught by java compiler (javac) or JVM. Finding out those errors is the responsibility of the programmer only. Note : by comparing the output of a program with the manually calculated result the programmer can find the presence of a logical error. Run-time error : A run- time error is called as exception. An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions are detected by JVM at run-time. Consider the following code : class demo { public static void main() { System.out.println("this is my first java program"); } } The above code can be compiled but we cannot execute(run) the code. Since when ever we run the code using statement java demo it generated error since JVM cant find main() method with String args*+ in the above code. So it generates an error.

Cant we call compile-time error as compile-time exception ? The reason for this is that an exception is something thrown during execution of a program. Java has a specific type for this, the Exception class.At compile time, your code is not executing, so it cannot throw an exception. Indeed, it is proper execution of the compiler to find errors in your code - certainly not an exception case. Exception is something more of an unexpected flow that can be handled. Compile time error is more like invalid code..so code doesn't even compile.. Hence term "error" since it denotes more serious problem which has to be fixed.

All exceptions occur at run-time only. But some exceptions are detected at run-time and some are detected at compile-time. The exceptions that are checked at compilation-time by java compiler are called as CHECKED EXCEPTIONS and that are checked by JVM are called as UNCHECKED EXCEPTIONS. Unchecked exceptions and errors are considered as unrecoverable and the programmer cannot do anything when they occur. The programmer can write a java program with unchecked exceptions and errors and can compile the program. He can see their effect only when he runs the program. So java compiler allows him to write a java program without handling the unchecked exception and errors. In case of checked exceptions the programmer should either handle them or throw them without handling them. He cannot simply ignore them as java compiler would remind him of those errors. Consider the following statement : public static void main(String args[]) throws IOException here, IOException is an example for checked exception. So we threw it out of main() without handling it. This is done by throws clause written after main(). We can also handle it using try and catch blocks. Suppose we are not even throwing and handling then the java compiler will raise an error. The point is that an exception occurs only at run-time. But a checked exception, whether we handle it or not it is detected at compilation time. So exception can be defined as run-time error that can be handled by programmer. That is in case of exception the programmer can do something to avoid it. But in case of error programmer cannot do anything and hence if error occurs it causes some damage. All exceptions are declared as classes in java. Of course everything is a class in java. Even the errors are also represented as classes. All these classes are descendants of a super class called as throwable.

Exceptions can be handled by using the following mechanisms:1. try 2. catch 3. throw 4. throws 5. finally try block : The programmer should observe the statements in his program where there may be a possibility of exceptions. Such statements should be written inside try block. A try block looks as follows :try { Statements; } Try block first finds the error with in code limit and then throws it to catch block. Each and every try block should have a minimum of one catch block. The greatness of try block is that even if some exception arises inside it, the program will not be terminated. When JVM understands that there is an exception it stores the exception details in an exception stack and then jumps into catch block.

Catch block: Catch block catches the error thrown by try block and then prints them. Catch block specifies the type of error. A catch block looks as follows :catch (ExceptionClass reference) { Statements; } The reference variable above is automatically adjusted to refer the exception stack where the details of the exception are available and those details can be displayed using the statement System.out.println(reference); and also by using printStackTrace() method of throwable class which fetches the details of exception from the exception stack. Finally block: After writing try and catch blocks the programmer should ensure that clean up operations like closing the files and terminating the threads. The programmer should write this code in the finally block. Statements in finally block are executed irrespective whether there is an exception or not in the program. The finally block looks as follows :finally { Statements; } This ensures that all the opened files are properly closed and all the running threads are properly terminated. So the data in the files will not be corrupted and the user in on safe side. Note: Performing the above tasks is called as exception handling. Remember in exception handling the programmer is not preventing the exception, as in many cases it is not possible. But the programmer is avoiding any damage that may happen to user data.

Types of exceptions:
Exception class ArithmeticException ArrayIndexOutOfBoundsException Meaning Thrown when an exceptional condition has occurred in an arithmetic exception Thrown to indicate that an array has been accessed an illegal index. The index is either negative or greater that equal to the size of array. This exception is raised when we try to access a class whose definition is not found This exception is raised when we cant access or open a file. Thrown when a thread is waiting,sleeping or doing some processing and is interrupted. Thrown when a clas does not contain the field or the variable that is specified. Thrown when a method is not able to access. It is raised when referring to the members of a null objects. Null represents nothing. It is raised when a method could not convert a string into numeric format. It represents any exception which occurs during runtime. Thrown by string class methods to indicate that an index is either negative or greater than the size of string.

ClassNotFoundException FileNotFoundException InterruptedException NoSuchFieldException NoSuchMethodException NullPointerException NumberFormatException RuntimeException StringIndexOutOfBoundsException

PROGRAM-1: Program to demonstrate exception handling class exceptiondemo { public static void main(String[] args) { try { System.out.println("open files"); int n = args.length; System.out.println(" n = "+ n); int a = 45/n; System.out.println("a = "+a); }

catch(ArithmeticException ae) { ae.printStackTrace(); System.out.println(ae); System.out.println("please enter data while running the program"); } finally { System.out.println("close files"); } } } PROGRAM-2: Program to handle multiple exceptions class exceptiondemo1 { public static void main(String[] args) { try { System.out.println("open files"); int n = args.length; System.out.println(" n = "+ n); int a = 45/n; System.out.println("a = "+a); int b[] = { 10,20,30}; b[50]=100; } catch(ArithmeticException ae) { System.out.println(ae); System.out.println("please enter data while running the program"); } catch(ArrayIndexOutOfBoundsException aie) { aie.printStackTrace(); System.out.println("please see that array index is with in the range"); }

finally { System.out.println("close files"); } } } Output :

In the above program, there is provision for two exceptions ArithmeticException & ArrayIndexOutOfBoundsException These exceptions are handled with the help of two catch blocks. In the above output, when values are not passed while running the program one exception had occurred that is ArithmeticException and when we are passing some values another exception is raising that is, ArrayIndexOutOfBoundsException. This means even if there is scope for multiple exceptions, only one exception at a time will occur. throw clause : The throw keyword is used to throw exceptions. Syntax : throw exception;

Where the exception must be evaluated to an instance of Throwable class or it may subclasses. The throw statement in commonly used for user defined exceptions.

Program to demonstrate throw clause class throwtest { static void test(Object o) { System.out.println(o.toString()); } static void mythrow() { try { throw new NullPointerException("this is done"); } catch( NullPointerException e) { System.out.println("inside my throw"); throw e; } } public static void main(String[] args) { try { test(null); } catch(NullPointerException e) { mythrow(); } } }

Output :

throws clause : Even if the programmer is not handling runtime exceptions, the java compiler will not give any error related to runtime exceptions. But the rule is that the programmer should handle checked exceptions. In case the programmer does not want to handle the checked exceptions, he should throw them out using throws clause. Otherwise, there will be an error raised by java compiler. Program to demonstrate throws keyword import java.io.*; class sample { String name; void accept() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter name"); name = br.readLine(); } void display() { System.out.println("name = "+name); } } class exceptiondemo2 { public static void main(String[] args) throws IOException

{ sample s = new sample(); s.accept(); s.display(); } } Output :

If throws IOException is not written after main() and accept() then :-

If throws IOException is not written after main() then :-

USER-DEFINNED EXCEPTIONS Program to create user-defined exceptions


class OwnException extends Exception { OwnException(String msg) { super(msg); } } class MyException { public static void main(String a[]) { int marks=Integer.parseInt(a[0]); try { if(marks<0 || marks>100) { throw new OwnException("Marks should be in b/w 0 to 100"); } else System.out.println("entered marks are"+marks); } catch(OwnException e) { System.out.println(e.getMessage()); } } } Output :

Potrebbero piacerti anche