[go: up one dir, main page]

0% found this document useful (0 votes)
38 views49 pages

Exception Handling PPT-1

Exception handling in oops

Uploaded by

riyaknp2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views49 pages

Exception Handling PPT-1

Exception handling in oops

Uploaded by

riyaknp2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

OOPs with Java

Dr Amit Yadav
Exception Handling
Exception Handling

The exception handling in java is one of the powerful mechanism to handle


the runtime errors so that normal flow of the application can be maintained.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception.

1. Checked Exception

2. Unchecked Exception

3. Error
Difference between checked and
unchecked exceptions
Checked Exception: Checked exceptions are checked at compile-time.

The classes that extend Throwable class except RuntimeException and


Error are known as checked exceptions e.g. IOException, SQLException
etc.
Unchecked Exception: Unchecked exceptions are not checked at compile-
time rather they are checked at run time.

The classes that extend RuntimeException are known as unchecked


exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.

Error: Error is irrecoverable e.g. OutOfMemoryError,


VirtualMachineError, AssertionErroretc.
Hierarchy of Java Exception classes
Java try block

Java try block is used to enclose the code that might throw an exception. It
must be used within the method.

Java try block must be followed by either catch or finally block.


Java Exception Keywords
Java provides five keywords that are used to handle the exception.
Common Java Exceptions
➢ ArithmeticException

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0; //ArithmeticException

➢ NullPointerException

If we have a null value in any variable, performing any operation on the


variable throws a NullPointerException.

String s=null;
System.out.println(s.length()); //NullPointerException
➢ NumberFormatException

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException.

String s="abc";
int i=Integer.parseInt(s); //NumberFormatException

➢ ArrayIndexOutOfBoundsException

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException


occurs.

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException
java Exceptions Handling Index
1.Java Try-Catch Block
2.Java Multiple Catch Block
3.Java Finally Block
4.Java Throw Keyword
5.Java Throws Keyword
6.Java Throw vs Throws
7.Java Final vs Finally vs Finalize
8.Java Custom Exceptions
Syntax of java try-catch

try
{
//code that may throwexception
}
catch(Exception_class_Name ref)
{

}
Syntax of try-finally block
try
{
//code that may throwexception
}

finally
{

}
Problem without exception handling

public class Testtrycatch1{


public static void main(String args[])
{
int data=50/0; //may throw exception
System.out.println("rest of thecode...");
}
}

Output:
Exception in thread main java.lang.ArithmeticException:/ byzero
Solution by exception handling
public class Testtrycatch2
{
public static void main(String args[])
{
try{
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}

Output:
Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...
Java Multi catch block
public classTestMultipleCatchBlock{
public static void main(Stringargs[]){
try
{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("task1 iscompleted");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("task 2 completed");
}
catch(Exception e)
{
System.out.println("common taskcompleted");
}
System.out.println("rest of the code...");
}}
Output:
task1 completed rest of the code...
Java Nested try block
➢ In Java, using a try block inside another try block is permitted.

➢ For example, the inner try block can be used to handle


ArrayIndexOutOfBounds Exception while the outer try block can handle
the ArithemeticException (division by zero).
public class NestedTryBlock{
public static void main(String args[ ]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}

System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}

System.out.println("normal flow..");
}
}
Output:
Java finally block
➢ Java finally block is a block used to execute important code such as
closing the connection, etc.

➢ Java finally block is always executed whether an exception is handled or


not.

➢ finally block in Java can be used to put "cleanup" code such as closing a
file, closing connection, etc.

➢ The important statements to be printed can be placed in the finally block.


When an exception does not occur
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of phe code...");


}
}
Output:
When an exception occurs and is handled by the catch block
public class TestFinallyBlock2{
public static void main(String args[]){

try {

System.out.println("Inside try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}

//handles the Arithmetic Exception / Divide by zero exception


catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of the code...");


}
}

Output:
Java throw keyword

➢ The Java throw keyword is used to throw an exception explicitly.

➢ We can throw either checked or unchecked exceptions in Java by


throw keyword.

➢ It is mainly used to throw a custom exception.

➢ For example, we can throw ArithmeticException if we divide a


number by another number.

➢ Syntax:
throw new exception_class("error message");

➢ Ex:
throw new IOException("sorry device error");
Throwing Unchecked Exception
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Java Exception Propagation
➢ An exception is first thrown from the top of the stack and if it is not
caught, it drops down the call stack to the previous method
class TestExceptionPropagation{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
Java throws keyword
➢ The Java throws keyword is used to declare an exception.

➢ It gives an information to the programmer that there may occur an


exception.

➢ Syntax:

return_type method_name() throws exception_class_name{


//method code
}
Which exception should be declared?
➢ Checked exception only, because:

•unchecked exception: under our control so we can correct our code.

•error: beyond our control. For example, we are unable to do anything if


there occurs VirtualMachineError or StackOverflowError.
Ex 1:
import java.io.IOException;
class Testthrows1{
void m() throws IOException{
throw new IOException("device error");//checked exception
}
void n() throws IOException{
m();
}
void p(){
try{
n( );
}
catch(Exception e)
{
System.out.println("exception handled");
}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p( );
System.out.println("normal flow...");
}
}
Difference between throw and throws in Java
➢ The throw keyword throw the exception explicitly from a method or a
block of code whereas the throws keyword is used in signature of the
method.
Java throw and throws Example
public class TestThrowAndThrows
{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}

Output:
Difference between final, finally and finalize
➢ The final, finally, and finalize are keywords in Java that are used in
exception handling.

➢ The basic difference between final, finally and finalize is that the final is
an access modifier, finally is the block in Exception Handling
and finalize is the method of object class.
Java Custom Exception

➢ In Java, we can create our own exceptions that are derived classes of the
Exception class.

➢ Creating our own Exception is known as custom exception or user-


defined exception.

➢ Basically, Java custom exceptions are used to customize the exception


according to user need.
Example: InvalidAgeException class extends the Exception class.
//class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{

// method to check the age


static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object


System.out.println("Exception occured: " + ex);
}

System.out.println("rest of the code...");


}
}

You might also like