Exception_Handling_Tutorial
Exception_Handling_Tutorial
Exception Handling
Q. what is exception
__________________________________________________________________________
Exception is events which occur at program run time and which is responsible for disturb normal flow of
application called as exception.
if we think about above code we get run time error java.lang.ArithmeticException because we input two
values first is 9 and second is 0 so 9/0 is infinity and system cannot calculate infinity .
try : try is a block which is used for write a code in which exception may be occur when exception
generate in program then JVM create exception object in try block as per the exception and pass to
catch block means in short we can say we can write code try block there is possibility of exception.
catch: catch block is used for writing logic those want to execute after exception
means we can catch block always executed if exception generate by try block means catch block is
responsible for handle exception.
Syntax:
try{
write here logics in which exception may be occur
}
catch(exceptiontype ref)
{ write here logics after exception
}
single try can have more than one catch block.
try{
write here logics in which exception may be occur
}
catch(exceptiontype ref)
{ write here logics after exception
}
catch(exception type ref)
{
}
finally : finally is block which always execute if exception generate in program or not
we can use finally with try and with try and catch also
try{
}
catch(exception type ref){
}
finally{
}
or
try{
}
finally{
}
}
finally{
}
throw: throw is clause in exception handling which is always use for throw the user defined exceptions.
throws: throws is clause in exception handling which is used for handle the checked exceptions.
catch(NumberFormatException ex) {
System.out.println("Error is "+ex);
}
}
}
InputMismatchException : this occur by JVM when user provide wrong type of input
package org.techhub;
import java.util.*;
public class ArrayIndexApplication {
public static void main(String[] args) {
try {
Scanner xyz = new Scanner(System.in);
System.out.println("Enter value");
int val=xyz.nextInt();
int sq=val*val;
System.out.printf("Square is %d\n", sq);
}
catch(InputMismatchException ex)
{
System.out.println("Error is "+ex);
}
}
}
finally block :
finally block is execute always if exception generate in program or not
means finally block execute always in any situation
syntax:
try{
}
finally{
}
or
try{
}
catch(exception ref)
{
}
finally
{
}
try{
}
finally{
}
Note: when we use finally with try then we need to know some important points.
1) Finally only execute its own block not handle exception
2) When exception generate code then finally execute very first before try also.
Source code
package org.techhub;
import java.util.*;
public class ArrayIndexApplication {
public static void main(String[] args) {
Scanner xyz = new Scanner(System.in);
try {
int a, b, c;
System.out.println("Enter two values");
a = xyz.nextInt();
b = xyz.nextInt();
c = a / b;
System.out.println("Division is " + c);
} finally {
System.out.println("I can execute always");
}
System.out.println("Logic1");
System.out.println("Logic2");
System.out.println("Logic3");
System.out.println("Logic4");
}
}
thorws : throws is a clause in exception handling and which is used for handle checked exception and it
only works with a function and when we use throws then we need to write try and catch at function
calling point.
Syntax of throws :
returntype functionname(arguments)throws exceptiontype
{
}
why throws use with a function definition
_________________________________________________________
we use function for code reusability purpose means when we define any function then we reuse it
means function define single person but can use by multiple purpose but when function contain
maximum possibility of exception so we need to generate exception warning at function calling
pointer or at compile time so this is main reason throws use with function definition.
package org.techhub;
import java.util.*;
class Div
{ void setValue(int x,int y)throws ArithmeticException,ClassNotFoundException
{
System.out.println("Division is "+(x/y));
}
}
public class ArrayIndexApplication {
public static void main(String[] args)
{
try {
Div d = new Div();
d.setValue(5, 0);
}
catch(Exception ex) {
System.out.println("Error is "+ex);
}
}
}
throw keyword : throw keyword is used for handle user defined exceptions
_________________________________________________________________
User defined exception means those exception generated by user or
if we user create own classes for exception handling purpose called as user defined exceptions.
Example: we want to create application for admission process of school and when we input the adhar
number of student then system should calculate automatically age of student and if age of student is
less than 6 year then system should generate error to us at run time invalid admission age
Here we have to design following classes
1) class Adhar : Adhar class contain info of student like as name,dob ,address and adhar is POJO.
2) class AdmissionException : this class generate exception or error for admission at run time.
this class contain one method name as
String getAdmissionError(): this method return error related with admission
3) EnrollNewAdmission: this class can accept name admission and in this class contain one method
name as
void newAdmission(Adhar info): this method accept adhar info student and calculate its age as well
as cross verify its age with six year if age is less than six year then throw new exception name as
AdmissionException at function calling point otherwise display message welcome in school.
4) UserDefinedExceptionApplication: this class contain main method here we can create object of
EnrollNewAdmission class and create object of Adhar class and store student info in it and pass to
EnrollNewAdmission class and handle AdmissionException .
}
public Adhar(String name,String adharNumber,String dob,String address) {
this.name=name;
this.adharNumber=adharNumber;
https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 10
GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265
this.address=address;
this.dob=dob;
}
public String getAdharNumber() {
return adharNumber;
}
public void setAdharNumber(String adharNumber) {
this.adharNumber = adharNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
package org.techhub;
import java.util.Date;
package org.techhub;
import java.util.*;
public class UserDefinedExceptionApplication {
public static void main(String[] args) {
Scanner xyz = new Scanner(System.in);
System.out.println("Enter name dob(date-month-year) address and adhar number of student");
String name=xyz.nextLine();
String dob=xyz.nextLine();
String address=xyz.nextLine();
String adharNo=xyz.nextLine();
Adhar ad = new Adhar(name,adharNo,dob,address);
try {
EnrollNewAdmission adm = new EnrollNewAdmission();
adm.newAdmission(ad);
}
catch(AdmissionException ex) {
System.out.println(ex.getAdmissionError());
}
}
}
Answer: (C)
Explanation: In Java only throwable objects (Throwable objects are instances of any subclass of the
Throwable class) can be thrown as exception. So basic data type cannot be thrown at all. Following are
errors in the above program.
Question 2: what will be the output of given code?
class Test extends Exception {
}
class Main {
public static void main (String args[]) {
try {
throw new Test();
}
catch(Test t) {
System.out.println("Got the Test Exception");
}
finally {
System.out.println("Inside finally block ");
}
}
}
Options
(A) Got the Test Exception
Inside finally block
Answer: (A)
Explanation: In Java, the finally is always executed after the try-catch block. This block can be used to do
the common cleanup work. There is no such block in C++.
Answer: (C)
Explanation: ArithmeticException is an unchecked exception, i.e.,
not checked by the compiler. So the program compiles fine. See following for more details.
Explanation: On division of 20 by 0, divide by zero exception occurs and control goes inside the catch
block. Also, the finally block is always executed whether an exception occurs or not.
{
try
{
int a[]= {1, 2, 3, 4};
for (int i = 1; i <= 4; i++)
{
System.out.println ("a[" + i + "]=" + a[i] + "n");
}
}
catch (Exception e)
{ System.out.println ("error = " + e);
}
catch (ArrayIndexOutOfBoundsException e)
{ System.out.println ("ArrayIndexOutOfBoundsException");
}
}
}
Options
(A) Compiler error
(B) Run time error
(C) ArrayIndexOutOfBoundsException
(D) Error Code is printed
(E) Array is printed
Answer: (A)
Explanation: ArrayIndexOutOfBoundsException has been already caught by base class Exception. When
a subclass exception is mentioned after base class exception, then error occurs.