Exception handling in Java
Exception :
Exceptions are exceptional/unusual/abnormal events that occur during the execution of programs.
An abnormal condition that disrupts Normal program flow.
Exception handling :
Exception Handling is a mechanism to handle runtime error.
Exception Handling is mainly used to handle the checked exceptions.
If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.
How the exceptions are handled. Explain exception handling mechanism?
Exceptions in java are handled using try, catch and finally blocks.
try block : The code or set of statements which are to be monitored for exception are kept in this block.
Java try block is used to enclose the code that might throw an exception. It must be used within the method. The code that can cause exception is placed within try block.
Java try block must be followed by either catch or finally block.
catch block : This block catches the exceptions occurred in the try block.
Java catch block is used to handle the Exception. It must be used after the try block only.
Throw :The keyword “throw” is used to throw the exception explicitly.
We can throw either checked or uncheked exception in java by throw keyword.
The throw keyword is mainly used to throw custom exception.
Throws :A keyword used to specify a set of exceptions a method might throw during its execution.
Java throws keyword is used to declare an exception. Used in method signature.
Syntax:
Type method_name(parameters) throws Exception lists;
Each Exception separated by commas.
finally block : This block is always executed whether exception is occurred in the try block or not and occurred exception is caught in the catch block or not.
finally block is always executed no matter whether there is an exception or not. It is used to handle or execute the important code.
The finally block is optional there can be only one finally block.
Syntax for Exception Handling :
try
{
//erroneous code
throw obj;
}
catch(ExceptionType1 e)
{
//catch block
}
finally
{
//This block is always executed.
}
Significance of finally block :
Finally block is used to specify any cleanup code. To Free resources such as closing file, database connection,net connection, I/O stream, etc.
The finally block is a key tool for preventing resource leaks.
Finally block is used to release resources like I/O buffer , connection, etc.
Cases when the finally block doesn’t execute
The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.
Write a java program to identify the significance of finally block in handling exceptions.
program :
class Test
{
public static void main(String args[])
{
try
{
int c=25/0;
System.out.println(c);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
finally block is always executed
Exception in thread main java.lang.ArithmeticException: / by zero
Write a java program to implement exception handling using multiple
catch statements.
public class multiplecatchblock
{
public static void main(String args[])
{
try {
double c;
int a=10, b=0;
c=a/b;
int x[]=new int[4];
x[5]=8;
}
catch(ArithmeticException e)
{
System.out.println ("Error:division by Zero occurred");
}
catch(NullPointerException e)
{
System.out.println("Error:null pointer exception");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println ("Error:index out of range occurred.");
}
catch(Exception e)
{
System.out.println (" Error:something went wrong in code");
}
finally
{
System.out.println("rest of the code");
}
}
}
Custom Exceptions :
User-defined Exceptions are defined by the user/programmer.
This can be done by creating a user defined class extending the Exception class
Syntax:
Class <MyExceptionClass> extends Exception
{
//statements
}
User can throw the exception he created by using throw keyword.
Write a program to implement the concept of Exception Handling by creating user defined exceptions.
Two ways you can can throw the user Exception.
Note :(You can write any one Example among them either program1 or program 2.)
Syntax 1:
<MyExceptionClass> obj = new MyExceptionClass(“arguments”);
throw obj;
Program 1 :
class myException1 extends Exception
{
public String toString()
{
return "User-Defined Exception";
}
public static void main(String args[])
{
myException1 ob= new myException1();
try
{ throw ob;
}
catch(myException1 e)
{
System.out.println("Exception handled - "+ e);
}
}
}
Output :
Exception handled - User-Defined Exception
Syntax 2:
throw new MyExceptionClass();
program 2:
import java.io. *;
class myexception extends Exception
{
myexception(String s)
{
super(s);
}
}
class user
{
public static void main(String argv[ ])throws myexception
{
int age=25;
if( age<18)
{
throw new myexception ("person is not eligible for vote because age is:"+age);
}
else
{
System.out.println("person is eligible for vote because age is:"+age);
}
}
}
Output:
person is eligible for vote because age is:25
Or
Exception in thread "main" myexception: person is not eligible for vote because age is:
at user.main(user.java:16)
Program 3:
Write a program in java if number is less than 10 and greater than 50 it generate the exception out of range. Else it
displays the square of number.
Program code:
class CustomTest
{
public static void main(String arr[])
{
try
{
int a=Integer.parseInt(arr[0]);
if(a<10|| a>50)
throw(new outofRangeException("valid range is 10 to 50"));
{
int s=a*a;
System.out.println("Square is:"+s);
}
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
Program 4:
Write a program in java to enter the number through command line argument if first and second number is not
entered it will generate the exception. Also divide the first number with second number and generate the exception if the second number is zero.
program code:
class Divide
{
public static void main(String args[])
{
try
{
if(args.length<2)
throw(new Exception("two argument must be provided"));
int a= Integer.parseInt(arr[0]);
int b=Integer.parseInt(arr[1]);
if(b==0)
throw(new Exception("second argument should be non zero"));
int c=a/b;
System.out.println("result:"+c);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Hi sir. plz upload Post on exception hierarchy
ReplyDelete