Previous | Home | Next |
Exception is error that raised in programs during run time. Exception can be raise bcause:
-
A user has entered invalid data or
-
A file that needs to be opened cannot be found or
-
A network connection has been lost in the middle of communications, or the JVM has run out of memory.
Except above there may be many other reasons.
When Exception raise in method it creates an object. This object called Exception Object contains all information regarding error and state of program.
Exception Handling Mechanism
When Exception object raised it must be handle otherwise program will terminate. Java use five key words called exception handling
- try
- catch
- throw
- throws
- finally
try { //block monitors error } catch(exceptiontype e) { //exception handler } finally { // block will must execute before try ends }
Try block contains code where exception may generate. Exception raised caught by catch block. The code that must execute before a method returns or program terminated must be written in finally block. Exception type shows type of exception raised . One example of Java exception is given below.
Example
/* * Saved as excpexmp1.java * Show use of try and catch block */ package exceptionhandling; class Excp{ int dividend,divisor; Excp(int n1,int n2) { divisor=n1; dividend =n2; } public int div() { int i=0; try{ i=dividend/divisor; }catch(ArithmeticException e) { System.out.println("Divide by zero"); } return i; } } public class excpexmp1 { public static void main(String[] str) { Excp obj=new Excp(10,20); Excp ob1= new Excp(0,10); System.out.println(obj.div()); System.out.println(ob1.div()); } }
Output:
2 Divide by zero 0
Previous | Home | Next |