Unit 4 (Java)
Unit 4 (Java)
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.
Some errors can halt the execution of a program and the program is terminated from the
statement where the error has occurred.These run time errors are called
exceptions.Programmer has to handle the exceptions to have a smooth execution of a
program.
In JAVA exceptions can be handled by try and catch block.The statements which may raise
an exceptions are written inside try block.The exceptions raised by try block are handled by
catch block.In catch block the exception is handled by printing some message.
e.g.
try
catch(exception exceptionname)
Page | 1
UNIT-IV
Types of Exception
Exceptions can be of 2 types:
❖ Checked Exception
❖ Unchecked Exception
Checked Exceptions:
Checked Exceptions are those which can be found during the compilation are called the
checked exceptions.
Unchecked Exceptions:
There are given some scenarios where unchecked exceptions can occur. They are as
follows:
If we have null value in any variable, performing any operation by the variable occurs
an NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException
Page | 2
UNIT-IV
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an illegal index. The index
is either negative or greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is
interrupted.
Page | 3
UNIT-IV
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null
represents nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric
format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than
the size of the string
User-Defined Exceptions
User can design exception we can throw it at appropriate situation
Page | 4
UNIT-IV
A)ArithmeticException
class ExceptionDemo1
{
public static void main(String args[])
{
try
{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result = " +output);
}
catch(ArithmeticException e)
{
System.out.println ("Arithmetic Exception: You can't divide an integer by 0");
}
}
}
Page | 5
UNIT-IV
B)NumberFormatException
class ExceptionDemo2
{
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");
}
}
}
C) ArrayIndexOutOfBoundsException
class ExceptionDemo3
{
public static void main(String args[])
{
try
{
int a[]=new int[10];
//Array has only 10 elements
a[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println ("ArrayIndexOutOfBounds");
}
}
}
Page | 6
UNIT-IV
D) NullPointer Exception
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println("NullPointerException..");
}
}
}
E) StringIndexOutOfBoundsException
class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try
{
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println("StringIndexOutOfBoundsException");
}
}
}
Page | 7
UNIT-IV
❖ Java provides us facility to create our own exceptions which are basically derived
classes of Exception.
import java.io.*;
class myexception extends Exception
{
myexception(String s)
{
super(s);
}
}
class user
{
public static void main(String args[]) throws myexception
{
int marks=180;
if( marks > 100 )
{
throw new myexception ("marks are more than 100 ");
}
else
{
System.out.println("marks "+marks);
}
}
}
In the above example a userdefined exception called myexception which extended from
Exception class. Super is a function using which a constructor of a base class can be called.
Whenever marks are exceeding 100 exception is thrown with the keyword throw along with
the message.
Page | 8
UNIT-IV
TRY-CATCH-FINALLY BLOCK
class FinallyBlock1
{
public static void main(String args[])
{
int a[]={5,10};
int b=0;
try
{
int x=a[2]/b-a[1];
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index error");
}
finally
{
int y=a[1]/a[0];
System.out.println("value of y= "+y);
}
}
}
Page | 9
UNIT-IV
Example-1
class MultipleCatchBlock
{
public static void main(String args[])
{
int a[]={5,10};
int b=0;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index error");
}
catch(ArrayStoreException e)
{
System.out.println("wrong data type");
}
int y=a[1]/a[0];
System.out.println("value of y= "+y);
Page | 10
UNIT-IV
Example-2
class FinallyBlock
{
public static void main(String args[])
{
int a[]={5,10};
int b=0;
try
{
int x=a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index error");
}
catch(ArrayStoreException e)
{
System.out.println("wrong data type");
}
finally
{
int y=a[1]/a[0];
System.out.println("value of y= "+y);
}
}
}
Page | 11
UNIT-IV
throw exception;
In this example, we have created the validate method that takes integer value as a
parameter.If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.
class TestThrow
{
void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
}
class AE
{
public static void main(String args[])
{
TestThrow tt=new TestThrow();
tt.validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
Page | 12
UNIT-IV
Syntax of throws
//method code
import java.io.*;
class ThrowExample
{
void mymethod(int num) throws IOException, ClassNotFoundException
{
if(num==1)
throw new IOException("Exception Message1");
else
throw new ClassNotFoundException("Exception Message2");
}
}
Page | 13
UNIT-IV
class Demothrow
{
public static void main(String args[])
{
try
{
ThrowExample obj=new ThrowExample();
obj.mymethod(1);
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
1) Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to
declare an exception.
2) Checked exception cannot be propagated using throw only. Checked exception can be propagated
with throws.
4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple exceptions. You can throw multiple exceptions.
Page | 14
UNIT-IV
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("array index error");
}
finally
{
int y=a[1]/a[0];
System.out.println("value of y= "+y);
}
}
}
Page | 15
UNIT-IV
class TestGarbage
{
void finalize()
{
System.out.println("object is garbage collected");
}
{
TestGarbage s1=new TestGarbage();
TestGarbage s2=new TestGarbage();
s1=null;
s2=null;
System.gc();
}
}
Page | 16
UNIT-IV
class TestGarbage
{
void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage s1=new TestGarbage();
TestGarbage s2=new TestGarbage();
s1=null;
s2=null;
System.gc();
}
}
NOTE:
❖ The gc() method is used to invoke the garbage collector to perform cleanup
processing.
❖ The garbage collector finds these unused objects and deletes them to free up
memory.
❖ The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing.
Page | 17
UNIT-IV
Multithreading in Java
2) implement the run() method that is responsible for executing the sequence of code that
the thread will execute
3)create the thread object and call the start() method to initiate the thread execution
example
class Multithread
{
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}
Page | 18
UNIT-IV
3) create a thread by defining an object that is instantiated from this “runnable” class as the
target of that thread
Example
class Multithread1
{
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1=new Thread(m1);
t1.start();
}
Page | 19
UNIT-IV
{
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
}
class Test
{
public static void main(String args[])
{
Priority m1=new Priority();
Priority m2=new Priority();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Page | 20
UNIT-IV
Output:
t1.start();
t2.start();
}
}
Page | 21
UNIT-IV
OUTPUT
1
1
2
2
3
3
4
4
Synchronization
At times when more than one thread try to access a shared resource, we need to ensure
that resource will be used by only one thread at a time. The process by which this is
achieved is called synchronization. The synchronization keyword in java creates a block of
code referred to as critical section.
General Syntax :
synchronized (object)
{
//statement to be synchronized
}
Page | 22
UNIT-IV
Page | 23
UNIT-IV
OUTPUT:
D:\>javac Syncro.java
D:\>java Syncro
[welcome]
[programmer]
[new]
Page | 24
UNIT-IV
Page | 25