0% found this document useful (0 votes)
26 views29 pages

9.exception Hanling

Uploaded by

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

9.exception Hanling

Uploaded by

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

Exception Handling

What is an Exception
An exception is an unwanted or unexpected
event, which occurs during the execution of
a program i.e at run time, that disrupts the
normal flow of the program’s instructions.
and the program/Application terminates
abnormally.
An exception can occur for many different
reasons. Following are some scenarios where an
exception occurs.

• A user has entered an invalid data.


• A file that needs to be opened cannot be found.
• A network connection has been lost in the
middle of communications or the JVM has run
out of memory.
Exception
• Exception: An abnormal event in a program is
called Exception.
• Exception may occur at compile time or at
runtime.
• Exceptions which occur at compile time are
called Checked exceptions.
I. ClassNotFoundException
II. IllegalAccessException
III. NoSuchFieldException
IV. EOFException etc.
• Exceptions which occur at run time are called
Unchecked exceptions.
• E.g.: Array Index Out Of Bounds Exception,
Arithmetic Exception, Number Format
Exception etc.

I. ArithmeticException
II. ArrayIndexOutOfBoundsException
III.NullPointerException
IV.NegativeArraySizeException etc.
Why do exception occur
• An exception is a condition that is caused by a run
time error in the program
• Most common run-time errors are:-
->Division by zero.
->Accessing an element that is out of the range of array.
->Passing a parameter that is not in a valid range.
->Attempting to use a negative size for an array.
Purpose of Exception handling
mechanism:-
• The purpose of EHM is to provide a method to detect
and report an exceptional circumstance so that right
action can be taken.
• It performs the following tasks:-
1. find the problem which is called ‘Hit’ the exception.
2. Inform that an error has occurred. It is called ‘throw’
the exception.
3. Receive the error information which is called ‘catch’
the exception.
4. Take corrective actions called ‘Handle’ the
exception.
Java’s common Exceptions:-
1)Arithmetic Exception
2)Array index of bounds exception
3)Array store Exception
4)File not found exception
5)Out of memory exception
6) Null pointer exception
7) Number format exception
8)String index out of bound exception
9)Interrupted Exception
10) IO exception
ArithmeticException
class exception1 catch (ArithmeticException e)
{ {
public static void main(String // This block is to catch divide-
args[]) by-zero error
{ System.out.println("Error:
int num1, num2; Don't divide a number by zero");
try { }
// Try block to handle code that
may cause exception System.out.println("I'm out of try-
num1 = 0; catch block in Java.");
num2 = 62 / num1; }
System.out.println("Try block }
message");
}
Array index of bounds exception
public class ExceptionUnhandled
{
public static void main(String args[])
{
int marks[] = { 40, 50, 60 };
System.out.println("Hello 1");
int m1 = marks[3]; // permitted index numbers are 0, 1
and 2
System.out.println("Marks are " + m1);
System.out.println("Hello 2");
System.out.println("Hello 3");
}
}
ArrayStoreException
This exception is thrown when there has
been made an attempt to store the wrong
type of object into an array of objects.

The ArrayStoreException extends


RuntimeException , which means that it is
an exception thrown at the runtime
Example: ArrayStoreException
public class ArrayStoreE
{
public static void main(String... args) {

Object[] s = new Integer[4];

s[0] = 4.4;
}
}
Out of memory exception

OutOfMemoryError:
means that you’re doing something wrong,
either holding onto objects too long, or trying
to process too much data at a time. Sometimes,
it indicates a problem that’s out of your
control, such as a third-party library that
caches strings, or an application server that
doesn’t clean up after deploys.
Number format exception

This exception occurs when a


string is parsed to any numeric
variable.
Example
class NumberFormat
{
public static void main(String args[])
{
try
{
int num=Integer.parseInt ("XYZ") ;
System.out.println(num);
}
catch(NumberFormatException e)
{
System.out.println("Number format exception occurred");
}
}
}
Number format exception
statement int num=Integer.parseInt ("XYZ"); would
throw NumberFormatException because String
“XYZ” cannot be parsed to int.
String index out of bound exception

 An object of this class gets created whenever an


index is invoked of a string, which is not in the
range.
 Each character of a string object is stored in a
particular index starting from 0.
 To get a character present in a particular index
of a string we can use a method
charAt(int) of java.lang.String where int
argument is the index.
NullPointer Exception

An object of this class gets created whenever a


member is invoked with a “null” object.
Example
class NullPointer1
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}
catch(NullPointerException e)
{
System.out.println("NullPointerException..");
}
}
}
Methods of Exception handling in
java :-
5-keywords are mainly used. These are:-
-try
-catch
-throw
-finally
Advantages of Exception Handling
• Exception handling allows us to control the
normal flow of the program by using exception
handling in program.
• It throws an exception whenever a calling method
encounters an error providing that the calling
method takes care of that error.
• It also gives us the scope of organizing and
differentiating between different error types using
a separate block of codes. This is done with the
help of try-catch blocks.
Syntax of exception handling code:-

Try block
Exception object
created
throws
exception
object

Catch
exception handler
Dealing with Exceptions in Java
Multiple catch blocks in Java
1. A try block can have any number of catch
blocks.
2. A catch block that is written for catching the
class Exception can catch all other exceptions
Syntax:
public class TestMultipleCatchBlock
{
public static void main(String args[])
{
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed“);
}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed")
;}
catch(Exception e){System.out.println("common task completed");}

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


}
}
3. If multiple catch blocks are present in a
program then the above mentioned catch block
should be placed at the last as per the exception
handling best practices. throwing any
4. If the try block is not exception, the catch
block will be completely ignored and the
program continues.
5. If the try block throws an exception, the
appropriate catch block (if one exists) will
catch it
–catch(ArithmeticException e) is a catch block
that can catch ArithmeticException
Finally Statement
Java finally block is always
executed whether exception is
handled or not.
Java finally block follows try or
catch block
Exception doesn't occur.

class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally{System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
exception occurs and not handled.

class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed"
);}
System.out.println("rest of the code...");
}
}

You might also like