Skip to main content

Exception Handling

Exception Handling
  •  Exception is a run time error that occur due to abnormal condition and it
    disrupts the normal flow of program and it is necessary to handle it.
  • Process of handling the Exception is known as Exception handling.
  • To handle the Exception java provide try,catch and finally keyword.
How it work
  •  In real time Application your sensitive code where probability to occur exception is more that code we write in try block.
  •  If Exception occur then program flow goes to your catch block based on 
    exception. you can define any number of catch block.
  •  Now our requirement is whether Exception occur or not we want some code that always execute then that code we write in finally block.ex. in JDBC we closing statement for  some file or object.
Simple program to handle Exception
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
package exceptionHandling;
 
public class Sample 
{
 
	public static void main(String[] args)
	{
 
		System.out.println("****************************");
 
		int a=23;
		int b=0;
 
 
		try
		{
		   int c=a/b;
		}
 
		catch(ArithmeticException e)
		{
			System.out.println("exception handled successfully");
		}
 
		finally
		{
			System.out.println("this block is always executed ");
		}
 
		System.out.println("**********************************");
 
	}
}
 
output:
 
exception handled successfully
this block is always executed 
**********************************