An exception is an event, which occurs during the execution of the program, that an interrupt the normal flow of the program’s instruction. In other words, Exceptions are generated when a recognized condition, usually an error condition, arises during the execution of a method. Java includes a system for running exceptions, by tracking the potential for each method to throw specific exceptions.
For each method that could throw an exception, your code must report to the Java compiler that it could throw that exact exception. The compiler marks that method as potentially throwing that exception, and then need any code calling the method to handle the possible exception.
Exception handling is basically use five keyword as follows :
Exceptions are generated when an error condition occur during the execution of a method. It is possible that a statement might throw more than one kind of exception. Exception can be generated by Java-runtime system or they can be manually generated by code.
Error-Handling becomes a necessary while developing an application to account for exceptional situations that may occur during the program execution, such as
In this unit we will learn the exception handling mechanism.
Exceptions are generated when a recognized an error condition during the execution of a program. Java includes a system for running exceptions, by tracking the potential for each method to throw specific exceptions
There are two ways to handle an exception:
So, if you use a method in your code that is marked as throwing a particular exception, the compiler will not allow that code unless you handle the exception. If the exception occurs in a try block, the JVM looks to the catch block(s) that follow to see if any of them equivalent the exception type. The first one that matches will be executed. If none match, then this methods ends, and execution jumps to the method that called this one, at the point the call was made.
Following image shows the Exception type.
An error means fault and there are two types of error as follows:
Compile time errors :
Compiler time error means Java compiler identify the syntax error at the time of compilation. And without successfully compilation, compiler does not create .class file. That means we have to compile the program which should be error free and then compiler creates .class file of the program and then we can run the program.
The common problems are:
And so on.
//For example: class Try1 { public static void main(String args[]) { int a=12; int b=0; int c=a/b System.out.println("Division is+c); } } // O/P : C:\cc>javac Try1.java Try1.java:8: ‘;’ expected System.out.println("Division is+c); ^ Try1.java:8: unclosed string literal System.out.println("Division is+c); ^ 2 errors
Run time errors :
Several time program may compile successfully and compiler creates the .class file of the program but when the time of running the program, it shows the error and that type of error called run time error.
The common problems are :
//For example : write a program to find out division of two numbers. class Try1 { public static void main(String args[]) { int a=12; int b=0; int c=a/b; System.out.println("Division is"+c); } } // Output: C:\cc>javac Try1.java C:\cc>java Try1 Exception in thread "main" java.lang.ArithmeticException: / by zero at Try1.main(Try1.java:7)
try…catch :
If a method is going to resolve potential exception internally, the line of code that could generate the exception is placed inside a try block
//Syntax – try { code risky/unsafe code code that depends on the risky code succeeding }
There is usually at least one catch block immediately after the try block
//Syntax – catch (ExceptionClassName exceptionObjectName) { code using methods from exceptionObjectName }
If an exception occurs within a try block, execution jumps to the first catch block whose exception class matches the exception that occurred. Any steps remaining in the try block are skipped. If no exception occurs, then the catch blocks are skipped.
If declare a variable within a try block, it will not exist outside the try block, since the curly braces define the scope of the variable. You will often need that variable later, if nowhere else other than the catch or finally blocks, so you would need to declare the variable before the try.
If you declare but don't initialize a variable before a try block, and the only place you set a value for that variable is in the try block, then it is possible when execution leaves the try ... catch structure that the variable never received a value.
So, you would get a "possibly uninitialized value" error message from the compiler, since it actually keeps track of that sort of thing. Usually this happens with object references; you would also generally initialize them to null.
public class demo { public static void main(String[] args) { int ans1, ans2; int a = 2, b = 2, c = 0; try { ans1 = a/b; System.out.println("a/b = " + ans1); ans2 = a/c; System.out.println("a/c = " + ans2); } catch(ArithmeticException e) { System.out.println("Arithmetic Exception!"); } System.out.println("demo is over"); } } // Output: C:\>set path=C:\Java\jdk1.5.0_01\bin C:\>javac demo.java C:\>java demo a/b = 1 Arithmetic Exception! demo is over
Code Explanation –
The program will print the first result, and then not succeed while performing the division for the second equation. Execution will step to the catch block to print our message on the screen
//Example - The prior example used a RuntimeException, which your code is not obligated to handle. Most methods in the I/O classes throw IOException, which is an exception that you must handle. Following program shows the use of IOException.
import java.io.IOException; public class demo { public static void main(String[] args) { int num = 0; num = System.in.read(); try { num = System.in.read(); System.out.println("You entered " + (char) num); } catch (IOException e) { System.out.println("IO Exception occurred"); } } } // Output: C:\>javac demo.java demo.java:11: unreported exception java.io.IOException; must be caught or declared to be thrown num = System.in.read(); // comment out this line ^ 1 error
Code Explanation :
The line marked to comment out throws IOException, but is not in a try block, so the compiler rejects it. The second read attempt is within a try block, as it should be.
Using Multiple catch Blocks It is possible that a statement might throw more than one kind of exception
class demo { public static void main (String args []) { int A[ ] = new int [5]; try { for (int c = 0; c <5; c++) { //do nothing } for (int c = 0; c <5; c++) { A[c] = c/ c; } } catch (ArrayIndexOutOfBoundsException e) { System.out.println ("Array out of bound "); } catch (ArithmeticException e) { System.out.println ("Zero divide error"); } } } // Output: C:\>javac demo.java C:\>java demo Zero divide error C:\>
Finally Block :
To guarantee that a line of code runs, whether an exception occurs or not, use a finally block after the try and catch blocks The code in the finally block will almost always execute, even if an unhandled exception occurs; in fact, even if a return statement is encountered
//Syntax – try { risky code/ unsafe code block } catch (ExceptionClassName exceptionObjectName) { code to resolve problem } finally { code that will always execute }
You can throw an exception explicitly using the throw statement.
Example : You need to throw an exception when a user enters a wrong student ID or password.
The throws clause is used to list the types of exception that can be thrown in the execution of a method in a program.
The throw statement accepts a single argument, which is an object of the Exception class.
//Syntax – throw ThrowableObj
You can use the following code to throw the IllegalStateException exception :
class demo { static void tdemo() { try { throw new IllegalStateException (); } catch (NullPointerException e) { System.out.println ("Not Caught by the catch block inside tdemo ()."); } } public static void main (String args[ ]) { try { tdemo(); } catch(IllegalStateException e) { System.out.println("Exception Caught in:"+e); } } } // O/P : C:\>javac demo.java C:\>java demo Exception Caught in:java.lang.IllegalStateException C:\>
The throws statement is used by a method to specify the types of exceptions the method throws. If a method is capable of raising an exception that it does not handle, the method must specify that the exception have to be handled by the calling method.
This is done using the throws statement. The throws clause lists the types of exceptions that a method might throw.
//Syntax – [< access specifier >] [< modifier >] < return type > < method name > [< arg list >] [ throws <exception list >]
//Example: You can use the following code to use the throws statement: class demo { static void throwMethod ( ) throws ClassNotFoundException { System.out.println ("In throwMethod "); throw new ClassNotFoundException ( ); } public static void main (String args [ ]) { try { throwMethod ( ); } catch ( ClassNotFoundException e) { System.out.println (" throwMethod has thrown an Exception :" +e); } } } Output C:\>javac demo.java C:\>java demo In throwMethod throw Method has thrown an Exception :java.lang.Class Not Found Exception
You can create your own exception class by extending an existing exception class
//Syntax – [modifiers] New Exception Class Name extends ExceptionClassName { create constructors that usually delegate to super-constructors }
You could then add any fields or methods that you wish, although often that is not required. You must, however, override any constructors you wish to use: Exception ( ), Exception(String message), Exception(String message, Throwable cause), Exception (Throwable cause). Usually you can just call the equivalent super-constructor. If you extend RuntimeException or one of its subclasses, your exception will be treated as a runtime exception.
When a situation arises for which you would like to throw the exception, use the throw keyword with a new object from your exception class, for example:
//Syntax – throw new ExceptionClassName(messageString);
All Rights Reserved. © 2024 BookOfNetwork