0% found this document useful (0 votes)
35 views25 pages

Unit 4 (Java)

This document provides a comprehensive overview of exception handling in Java, detailing what exceptions are, their types (checked and unchecked), and common scenarios where they occur. It explains the use of try-catch blocks for handling exceptions, the differences between the throw and throws keywords, and includes examples of various exceptions such as ArithmeticException and NullPointerException. Additionally, it covers user-defined exceptions, garbage collection, and multithreading in Java.
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)
35 views25 pages

Unit 4 (Java)

This document provides a comprehensive overview of exception handling in Java, detailing what exceptions are, their types (checked and unchecked), and common scenarios where they occur. It explains the use of try-catch blocks for handling exceptions, the differences between the throw and throws keywords, and includes examples of various exceptions such as ArithmeticException and NullPointerException. Additionally, it covers user-defined exceptions, garbage collection, and multithreading in Java.
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/ 25

UNIT-IV

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.

Some situations where exception may come are

1. Trying to divide a number by zero

2. Try to read from a file which does not exists

3. The file which we are trying to open does not exists

4. Trying to print an element of an array which is not there etc…

try and catch block

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

//statements which cause exception

catch(exception exceptionname)

//statements printing msgs

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.

Ex: ClassNotFoundException, NoSuchMethodException etc.

Unchecked Exceptions:

Unchecked Exceptions are those which can be found in the runtime.

Ex: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc

Common scenarios where exceptions may occur

There are given some scenarios where unchecked exceptions can occur. They are as
follows:

1) Scenario where ArithmeticException occurs

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


int a=50/0; //ArithmeticException

2) Scenario where NullPointerException occurs

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

3) Scenario where NumberFormatException occurs


The wrong formatting of any value, may occur NumberFormatException.
Suppose I have a string variable that have characters, converting this variable into digit will
occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException

4) Scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Types of Exception in Java

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

Common Types of Exception in Java with Examples

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

User defined Exception


❖ User can design exception we can throw it at appropriate situation.

❖ Java provides us facility to create our own exceptions which are basically derived
classes of Exception.

❖ For example MyException in below code extends the Exception class.


❖ We pass the string to the constructor of the super class

EXAMPLE TO DEMONSTRATE USER-DEFINED 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

MULTIPLE CATCH BLOCKS

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

Java throw keyword


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

The syntax of java throw keyword is given below.

throw exception;

java throw keyword example

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

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 so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.

Syntax of throws

return_type method_name() throws exception_class_name

//method code

EXAMPLE USING THROWS KEYWORD

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

Difference between throw and throws in Java

No. throw throws

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.

3) Throw is followed by an instance. Throws is followed by class.

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

Difference between final, finally and finalize

No. final finally finalize

1) final is a keyword. finally is a block. finalize is a method.

final keyword example


class FinalExample
{
public static void main(String[] args)
{
final int x=100;
x=200; //Compile Time Error
}
}

finally keyword example


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 | 15
UNIT-IV

finalize keyword example

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

Java Garbage Collection

Page | 16
UNIT-IV

Garbage Collection is process of reclaiming the runtime unused memory automatically. In


other words, it is a way to destroy the unused objects.

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

Multithreading in java is a process of executing multiple threads simultaneously.

There are two ways to create a thread


1. By extending Thread class
2. By implementing Runnable interface.

Extending Thread class

Steps for Extending the Thread class

1)declare the class as extending the Thread class

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 Multi extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
}

class Multithread
{
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
}
}

Page | 18
UNIT-IV

Implementing Runnable interface

Steps for implementing Runnable interface

1) declare the class as implementing the Runnable interface

2) implement the run() method

3) create a thread by defining an object that is instantiated from this “runnable” class as the
target of that thread

4) call the thread's start() method to run the thread

Example

class Multi3 implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}
}

class Multithread1
{
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1=new Thread(m1);
t1.start();
}

Page | 19
UNIT-IV

Priority of a Thread (Thread Priority)


Each thread have a priority. Priorities are represented by a number between 1 and 10.

3 constants defined in Thread class:

public static int MIN_PRIORITY


public static int NORM_PRIORITY
public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY).

The value of MIN_PRIORITY is 1

The value of MAX_PRIORITY is 10.

Example of priority of a Thread

class Priority extends Thread


{
void run()

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

running thread name is:Thread-0


running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

write a java program to demonstrate MultiThreading


class TestSleepMethod1 extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
class Test
{
public static void main(String args[])
{
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

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

Example using Synchronized block


class First
{
public void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}

class Second extends Thread


{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
public void run()
{
synchronized(fobj) //Synchronized block
{
fobj.display(msg);
}
}
}

public class Syncro


{
public static void main (String[] args)
{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1= new Second (fnew,"new");
Second ss2 = new Second(fnew, "programmer");
}
}

Page | 23
UNIT-IV

OUTPUT:

D:\>javac Syncro.java

D:\>java Syncro

[welcome]
[programmer]
[new]

Page | 24
UNIT-IV

Page | 25

You might also like