0% found this document useful (0 votes)
4 views

Exception_Handling_Tutorial

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Exception_Handling_Tutorial

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

GIRI’S TECH HUB – PVT.

LTD –PUNE - 9175444433, 9049361265

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 .

Why use Exception Handling or what is benefit of exception handling


1) Exception Handling help programmer to detect run time error
2) Exception Handling skip the code in which exception may be occur and execute remaining program
in safe zone.

There are three types of exception in Java


____________________________________________________________________________________
1) Checked Exception: those exception occur at program compile time called as checked exception the
major goal of checked exception is it provide precaution from exception at run time checked exception
help us to generate exception warning at compile time.
2) Unchecked Exception: unchecked exception means those exception occur at program run time called
as unchecked exception.
3) Error: Error is part of exception but the major diff between error and exception is error cannot handle
by programmer and exception can handle by programmer.
Means error are system generated
if we want to work with exception handling in java we have some inbuilt classes provided by java to us
as well as provide some keywords to us for handle exceptions.

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 1


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

Java Provide some inbuilt keyword to us for handle exception.

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

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 2


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

try{

}
catch(exception type ref){
}
finally{
}
or
try{
}
finally{
}

Q. can we write try without catch?


Yes becase if we try then using try we can finally directly there is no compulsion to use catch with try
every time if we have finally
try{

}
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.

Now we want to discuss about try and catch block


____________________________________________________________________________

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 3


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

ArrayIndexOutOfBoundsException: ArrayIndexOutOfBoundsException occur when we try to store more


than size of array.
package org.techhub;
public class ArrayIndexApplication {

public static void main(String[] args) {


try {
int a[]=new int[2]; //0 and 1 index
a[2]=200;
System.out.println("value is "+a[2]);
}catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Error is "+ex);
}
}
}

3) NullPointerException: NullPointerException when we use any reference without new keyword or


memory allocation
package org.techhub;
public class ArrayIndexApplication {
static int a[];
https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 4
GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

public static void main(String[] args) {


try {
a[0]=100;
System.out.println(a[0]);
}
catch(NullPointerException ex) {
System.out.println(ex);
}
}
}

4) NumberFormatException: NumberFormatException occur when we try to convert string value to


other type means perform conversion between string to integer, string to float etc
package org.techhub;

public class ArrayIndexApplication {


public static void main(String[] args) {
try { String s="12345 ";
int a=Integer.parseInt(s);
System.out.println("A is "+a);
}

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);

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 5


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

}
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
{
}

Q.can we write try without catch?


yes we can write try without catch block using finally block.
mean we can write try using a finally or when we write try using a finally then not need to write catch
block.

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

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 6


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

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");
}
}

Q. what is diff between finally and catch?


The major diff between finally and catch block is finally can execute only its own block but catch can
handle exception means catch block can handle exception but finally cannot handle exception
when we use finally and catch at same time then finally always write after catch.
Q. what is diff between final, finally and finalize?
__________________________________________________________________
final is keyword or non access specifier we can use with variable , function and class and it is used for
declare variable as constant , avoid method overriding and avoid inheritance.
finally is block which always execute in exception handling and execute some default code in exception
handline
finalize () is a method which is used for perform garbage collection.

throws and throw


________________________________________________________________________
throws and throw are the clauses in exception handling which is used for with a function and handle
exception at function calling point

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 7


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

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

Q. what is user defined exception?

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 8


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

_________________________________________________________________
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.

Q. why user needs to create user defined exceptions?


_________________________________________________________________________
1) If User having some run time error or some exception but java not provide any inbuilt API or class for
handle that exception so user can create own exception class and can handle exception.
2) If User Project required to generate custom error then user can create own exceptions called as user
defined exceptions.

Q. How to create User defined exceptions in Java?


___________________________________________________________________________________
if we want to create user defined exception in java we have to create own class and inherit any inbuilt
exception class in it

class MyArith extends ArithmeticException


{
}
when we create user defined exception and when we create object of user defined class and throw it
then JVM throw exception where function get call means we need to write try and catch at function
calling point.

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

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 9


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

EnrollNewAdmission class and create object of Adhar class and store student info in it and pass to
EnrollNewAdmission class and handle AdmissionException .

Source code Example


package org.techhub;

public class Adhar {

private String adharNumber;


private String name;
private String address;
private String dob;
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public Adhar() {

}
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;

public class AdmissionException extends ArithmeticException{

public String getAdmissionError() {


return "invalid admission age";
}
}
package org.techhub;

import java.util.Date;

public class EnrollNewAdmission {

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 11


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

public void newAdmission(Adhar adhar) {


Date d = new Date();
String s=d.toLocaleString();
String str[]=s.split(",");
String year[]=str[0].split("-");
String dob=adhar.getDob();
String udob[]=dob.split("-");
int age=Integer.parseInt(year[2])-Integer.parseInt(udob[2]);
if(age<6) {
AdmissionException ae = new AdmissionException();
throw ae; //throw user defined exceptions
}
else {
System.out.println("Welcome in school");
}
}
}

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());
}
}
}

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 12


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

Q. What is diff between throw and throws?


Throw Throws
Throw is used for handle user defined exceptions Throws is used for handle checked exception in
in java java
Throw can work with single exception class object Throws can handle or can use multiple exception
at time classes at same time with throws
If use throw then we need to create manual object If we use throws then we not need to create
exception class and throw it object of exception class JVM create object of
exception class and throw it.

Question 1: Predict the output of following Java program?


class Main {
public static void main(String args[]) {
try {
throw 10;
}
catch(int e) {
System.out.println("Got the Exception " + e);
}
}
}
Options
(A) Got the Exception 10
(B) Got the Exception 0
(C) Compiler Error

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();

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 13


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

}
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

(B) Got the Test Exception

(C) Inside finally block

(D) Compiler Error

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++.

Question 3: Output of following Java program?


class Main
{ public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
Options
(A) Compiler Error
(B) Compiles and runs fine
(C) Compiles fine but throws ArithmeticException exception

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.

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 14


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

Question 4: what will be the output of given code?


class Test
{ public static void main (String [] args)
{
try
{
int a = 0;
System.out.println ("a = " + a);
int b = 20 / a;
System.out.println ("b = " + b);
}
catch(ArithmeticException e) {
System.out.println ("Divide by zero error");
}
finally
{
System.out.println ("inside the finally block");
}
}
}
Options
(A) Compile error
(B) Divide by zero error
(C) a = 0
Divide by zero error
Inside the finally block
(D) a = 0
(E) Inside the finally block
Answer: (C)

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.

Question 5: what will be the output of given code ?


__________________________________________
class Test
{
public static void main(String[] args)

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 15


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

{
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.

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 16


GIRI’S TECH HUB – PVT.LTD –PUNE - 9175444433, 9049361265

https://techhubindia.org/ Download App – GIRI’S TECH HUB Page 17

You might also like