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

Unit 8 Exception Handling

Uploaded by

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

Unit 8 Exception Handling

Uploaded by

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

Exceptions and Exception Handling

Subject: Object Oriented Programming Language using JAVA

Faculty name: Bhushan Shewale


Exception: Abnormal Situation or Unexpected Event
1. It is an unexpected event or problem which occurs during execution of a program
(Runtime).
2. When an exception is occurred the program will stop abruptly(Forcefully).
Classification of Exception:
Que: What happens when an Exception Occurs?
Ans:

Yes

Yes No

Note:
1. In java all the exception are class of throwable type.
2. The exception will occurred because of statement.
3. The statement is responsible to generates an exception.
• Type of Exceptions

There are two types of Exception:

1. Checked Exception:

The compiler aware the exception are checked exception.

In this case our compiler already knows which particular statement is responsible to generate
an exception hence the compiler will force the programmer to either handled the exception or declared
the exception.

If not our compiler will never allow us to proceed further still if you try to proceed further we
will get Compile time error say in unreported exception.

Ex.

 InterruptedException

 FileNotFoundException
2. Unchecked Exception:

The compiler unaware exception are unchecked exception.

In this case our compiler don’t known which particular statement is responsible to
generate an exception.

Hence our compiler will not force the programmer to either handled and declared the
exception. Therefor we don’t get any compile time error even if we neither handled nor
declared the exception.

Ex. All the runtime exceptions and it’s subclasses along with error and it is subclasses are
unchecked exception.
• Throwable class:

1. Throwable class is the parent class of exception hierarchy.

2. It is defined in java.lang package.

3. In throwable class and it subclasses the toString( ) method is overridden in such a way
that it’s returns the fully qualified name of the exception along with reason.

4. The important methods throwable class are

i. public String getMessage( ) Method

ii. public void printStackTrace( ) Method


Note:

1. In throwable hierarchy the error class and it’s subclasses as well as runtime exception and
it’s subclass are considered as unchecked exception.

2. Exception class and it’s subclasses except runtime exception are considered as checked
exception.

3. The exception and throwable class are considered as partially checked classes.
• Exception Handling:

Exception handling is a mechanism which is used to continue the normal flow of


execution of a program. We can handled any type of exception by using try catch block.
Syntax:
try
{
//Statement;
}
catch(exception name + throwable type reference variable )
{
// Statement;
}
• try Block:

1. The statements which are responsible for causing an exception should be written inside
try Block.

2. When an exception occurs

a. The execution of program will paused

b. Throwable type object will get created

c. The reference of throwable type object will be passed to catch block.


• catch Block:

1. The catch block is used to stored the reference of throwable type object which is thrown by the try block.

2. When the catch block is capable of storing the reference of throwable object then we can say the exception
is handled. and that particular catch block will get executed.

3. if the catch block doesn’t store the reference of throwable type object then we can say exception is not
handled.

4. When the exception is handled normal flow will continues in case of the exception is not handled then the
program will stop abruptly.

Que: When we can say the exception got handled?

Ans: The throwable type reference variable which is declared inside catch block store the reference of throwable
type object then we can say the exception is handled.
• Important Exception
1. Arithmetic Exception

This is the most common cause of an Arithmetic Exception. For example, if you try to divide a
number by zero (e.g., int result = 5 / 0;), it will result in an Arithmetic Exception because dividing by
zero is undefined in mathematics. When you attempt to calculate the remainder of a division operation
by zero (e.g., int remainder = 10 % 0;), it will result in an Arithmetic Exception.

i. Arithmetic exception is raised.

ii. Arithmetic exception is a throwable type because throwable class is super most class.

iii. In this case the exception is occurred and not handled hence the program got stop abruptly.

In this example, when you attempt to divide numerator by denominator, which is zero, an
ArithmeticException is thrown, and the catch block handles the exception by printing a message.
Solution:
class Exception
{
public static void main (String [] args)
{
try
{
System.out.println("From try Block");
int a= 10/0;
System.out.println(a);
}
catch (ArithmeticException ae)
{
System.out.println("From Catch Block Exception got Handled");
}
}
}
2. Array Index Out of Bounds Exception

When we try to access the element which is not in the given range then we got
ArrayIndexOutOfBoundsException.

To prevent ArrayIndexOutOfBoundsException errors, always ensure that your array


indices are within the valid range (from 0 to array.length - 1) before accessing array elements.
You can use conditional statements, such as if or for loops, to check and handle these cases
gracefully to avoid runtime exceptions.
Solution:
class Exception
{
public static void main (String [] args)
{
try
{
System.out.println("From try Block");
int a [] = new int [5];
a [10] = 50;
}
catch (ArrayIndexOutOfBoundsException aoe)
{
System.out.println("Exception got Handled");
}
}
}
3. Class Cast Exception:
It is an unexpected event which occurs during execution of the program (Runtime). Class cast
Exception occurs during Down Casting process.
When we try to convert the parent type reference to a specific child type reference, and if this
object does not contain the instance of that particular type then we get class cast exception.
Solution:
class Parent
{
int a = 10;
int b = 20;
}
class Child extends Parent
{
int c = 30;
int d = 40;
}
class Driver
{
public static void main (String [] args)
{
Parent p1=new Parent ();
try
{
Child ch1=(Child)p1;
System.out.println(ch1.a);
System.out.println(ch1.b);
System.out.println(ch1.c);
System.out.println(ch1.d);
}
catch (ClassCastException cce)
{
System.out.println("Exception got Handled");
}
}
}
4. Null Pointer Exception:

When we try to perform some action on null value, we get null pointer exception. To
avoid NullPointerException errors, you should always check whether an object reference is
null before attempting to access its methods, variable, or elements. You can use conditional
statements, such as if or the null-safe operator ( in Java 8 and later), to handle these cases
gracefully and avoid unexpected runtime exceptions.
Solution:
class Exception
{
public static void main (String [] args)
{
try
{
System.out.println("From try Block");
String s=null;
System.out.println(s.toUpperCase()):
System.out.println(s.length());
}
catch (NullPointerException np)
{
System.out.println("Exception got handled");
}
}
}
5. Number Format Exception:

In Java, a NumberFormatException is thrown when you try to convert a string into a


numeric type (e.g., int, double, float, long) using methods like parseInt, parseDouble,
parseFloat, or constructors like Integer.parseInt, Double.parseDouble, etc., and the input
string does not represent a valid number in the expected format.
Solution:
class Exception
{
public static void main (String [] args)
{
try
{
System.out.println("From try Block");
String s="abc";
int i=Integer.parseInt(s);
}
catch (NumberFormatException nf)
{
System.out.println("Exception got Handled");
}
}
}
Throw:
Throw is a keyword which is used for throw the exception manually. Using throw keyword, we can
throw checked, unchecked exception, custom exception (user define exception).
Solution:
class Exception
{
public static void main (String [] args)
{
int a=10;
int b=20;
if(a<b)
{
throw new ArithmeticException ("Manually thrown");
}
else
{
System.out.println("Exception is not thrown");
}
}
}
Throws:
Throws is used to declared the exception back to the caller method. Throws keyword
should always used inside the method declaration statement. Using throws keyword, we can
be declaring multiple exception at the same time. And only checked exception are declare
using throws keyword.
Solution:
class Demo
{
public static void main (String [] args) throws InterruptedException
{
for (int i=1; i<=5; i++)
{
System.out.println(i);
Thread.sleep(2000);
}
}
}
• Finally Block:
Finally block can be used along with try catch block or only with try block.
Syntax:
try try
{ {
//Statement;
//Statement;
}
}
catch( )
{ finally
} {
finally }
{
}
Note: Finally block will get executed in any of the scenario or situation. Finally block will get
executed weather the exception is occurred or not occurred or exception is handled or not handled
finally block will get executed.
Ex.
Class Demo
{
public static void main (String [] args)
{
try
{
System.out.println(“From try Block”);
int a = 10;
}
catch(ArithmeticException ae)
{
System.out.println(“From catch Block”);
}
finally
{
System.out.println(“From finally Block”);
}
System.out.println(“Normal flow of execution”);
}
}

You might also like