Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

EXCEPTION HANDLING

❖ INTRODUCTION

● Errors are the mistakes that can make a program go wrong.


● An error may produce an incorrect output or terminate the execution of the
program abruptly or even may cause the system to crash, hence it is important to
detect and manage all the possible error conditions in the program properly so that
the program will not terminate or crash during execution.
TYPES OF ERRORS

1.Compile-time errors

2. Run-time errors

● All Syntax errors will be detected and displayed by the Java compiler and
therefore these errors are known as compile time errors.
● whenever the compiler displays an error it will not create the . class file hence it is
necessary to fix all the errors before we can successfully compiled and run the
program.
● Sometimes programs may accompany successfully creating in “.class” file but
may not run properly.
● such programs may produce wrong results due to wrong logic or may terminate
due to errors such as stack overflow .
❖ EXCEPTION
● An exception is a condition that is caused by run-time error in a program.
● when the Java interpreter encounters an error while running the
● program it creates an exception object and throws it.
● When exceptions occur in program the normal flow of program terminates, to
continue the execution of program exception should be handled properly by
executing a segment of code called as Exception Handler and this mechanism is
called as exception handling.
● Exception handling mechanism takes corrective actions to resolve exceptions that
has occurred in the program to continue the normal flow of program execution.

EXCEPTION TYPES
● Checked exceptions − A checked exception is an exception that is checked
(notified) by the compiler at compilation-time, these are also called as compile
time exceptions. These exceptions cannot simply be ignored, the programmer
should take care of (handle) these exceptions.
● Unchecked exceptions − An unchecked exception is an exception that occurs at
the time of execution. These are also called as Runtime Exceptions. These include
programming bugs, such as logic errors or improper use of an API. Runtime
exceptions are ignored at the time of compilation.

SYNTAX OF EXCEPTION HANDLING MECHANISM


try
{
// Code which might throw an exception
}
catch(Exceptionclass object1)
{
// code to handle an exception
}
catch(Exceptionclass object2)
{
// code to handle an exception
}
finally
{
// ALWAYS executed whether an exception was thrown or not
}
❖ EXCEPTION HANDLING USING try-catch

import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
MULTIPLE CATCH STATEMENTS

● If more than one exception can occur, then we use multiple catch blocks
● When an exception is thrown, each catch statement is inspected in order, and the
first one whose type matches that of the exception is executed
● After one catch statement executes, the others are bypassed
EXAMPLE:

public class MultipleCatchEx {


public static void main(String[] args) {
try{
int a=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

O/P: Arithmetic Exception occurs


rest of the code

❖ FINALLY
This block is executed whether an exception is handled or not.

EXAMPLE:
class FinallyExample{
public static void main(String[] args) {
try{
int a=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
finally{
System.out.println("finally block is executed");
}
}
}
O/P:
Arithmetic Exception Occures
finally block is executed

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

SYNTAX: throw new ThrowableInstance

● ThrowableInstance must be an object of type Throwable /subclass Throwable


EX:throw new IOException("sorry device error);

● We can throw either checked or uncheked exception in java by throw keyword.

EXAMPLE:

public class TestThrow{

void validate(int age){

if(age<18)

throw new ArithmeticException("not valid");

else

System.out.println("welcome to vote");

public static void main(String args[]){

TestThrow t1=new TestThrow();

t1. validate(13);

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

In the given example,age value is 13 hence condition (age<18) i.e., 13<18 becomes
true and Arithmetic exception will be thrown using “throw”.
O/P:

Exception in thread "main" java.lang.ArithmeticException: not valid


at TestThrow.validate(TestThrow.java:4)
at TestThrow.main(TestThrow.java:9)

THROWING CUSTOM EXCEPTIONS USING throw


● In java we can create our own exception class and throw our own exception using
throw keyword. These exceptions are known as user-defined or custom
exceptions.
● Java custom exceptions are used to customize the exception according to user
need.

EXAMPLE
import java.lang.*;
class MyException extends Exception{
MyException(int age)
{
if (age<18)
System.out.println("My Exception occurred,invalid age");
else
System.out.println("valid age");
}
}
public class Example1{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
throw new MyException(19);
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
O/P:
Starting of try block
valid age
Catch Block
MyException

In this example custom exception is thrown in Example1 class using ‘throw’ keyword in
try block,when exception is thrown MyException constructor of same class is invoked .
MyException class is consisting of user defined exception

❖ THROWS IN JAVA

● 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 to maintain the normal flow.
● Advantage of throws is it provides information to the caller of the method about
the exception.

return_type method_name() throws exception_class_name{

//method code

}
EXAMPLE

public class TestThrow{

void validate(int age) throws ArithmeticException{

if(age<18)

throw new ArithmeticException("not valid");

else

System.out.println("welcome to vote");

public static void main(String args[]){

TestThrow t1=new TestThrow();


t1. validate(13);

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

DIFFERENCE BETWEEN THROW AND THROWS

MULTITHREADING IN JAVA

INTRODUCTION

⦿ A Thread may be defined as a separate sequential flow of control within the main
program.
⦿ Threads are used in a program for achieving specific tasks.

⦿ Multithreading means, using different threads to perform different parts of a task.


⦿ In Multithreading, a task is divided into different subtasks and different threads,
which run simultaneously, for executing these subtasks.
⦿ Java provides Thread class to achieve thread programming.
⦿ Thread class provides constructors and methods to create and perform operations on
a thread.
⦿ Thread class extends Object class and implements Runnable interface.
MULTITASKING

⦿ Multitasking is a process of executing multiple tasks simultaneously.


⦿ Multitasking can be achieved by two ways:
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)
1) Process-based Multitasking (Multiprocessing)
⦿ Each process have its own address in memory i.e. each process allocates separate
memory area.
⦿ Process is heavyweight.
2) Thread-based Multitasking (Multithreading)
⦿ Threads share the same address space.
⦿ Thread is lightweight.
⦿ Multiprocessing and multithreading, both are used to achieve multitasking.
⦿ But we use multithreading than multiprocessing because threads share a common
memory area.
⦿ They don't allocate separate memory area so saves memory
⦿ Java Multithreading is mostly used in games, animation etc.
⦿ When multiple threads are created, they can be executed in any order.

THREAD LIFE CYCLE


⦿ During the life time of a Thread, there are many states it can enter,
⦿ they include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
1.Newborn State:
⦿ When we create a thread object, the thread is born and is said to be in newborn
state.
⦿ The thread is not yet scheduled for running.
⦿ At this state, we can do only one of the following things with it:
* Schedule it for running using start( ) method.
* Kill it using stop () method.

2. Runnable State:
⦿ The Runnable state means that the thread is ready for execution and is waiting for the
availability of the processor.
⦿ That is, the thread has joined the queue of threads that are waiting for execution.

3. Running State:
⦿ Running means that the processor has given its time to the thread for its execution.
⦿ The thread runs until it relinquishes (give up) control on its own.
Blocked State:
⦿ A thread is set to be blocked when it is prevented from entering into the Runnable
state and subsequently the running state.
⦿ This happens when the thread is suspended, or sleeping, or waiting in order to
satisfy certain requirements.
5. Dead State:
⦿ Every thread has a life cycle.
⦿ A running thread ends its life when it has completed executing its run ( ) method.
⦿ It is a natural death.
⦿ However, we can kill it by sending the stop message to it at any state thus causing
a premature death to it.
⦿ A thread can be killed as soon it is born, or while it is running, or even when it is
in “not Runnable” (blocked) condition.

CREATING THREADS
⦿ Java defines two ways by which a thread can be created.
1. By implementing the Runnable interface.
2. By extending the Thread class.

1.Creating thread by Implementing the Runnable Interface


⦿ The easiest way to create a thread is to create a class that implements the runnable
interface.
⦿ After implementing runnable interface , the class needs to implement the run()
method.public void run()
⦿ The implementation of run() inside thread class describes the action performed by
any thread.
Example 1:

class A implements Runnable


{
public void run()
{
System.out.println(“thread started running..");
}
}
Class Demo{
public static void main( String args[] ) {
A obj = new A();
Thread t = new Thread(obj);
t.start();
}
}

Output : thread started running..

⦿ To call the run() method, start() method is used.


⦿ On calling start(), a new stack is provided to the thread.

Example 2:
public class B implements Runnable {
public static void main(String[] args) {
B b1= new B();
Thread t = new Thread(b1);
t.start();
}
public void run() {
System.out.println("This code is running in a thread");
}
}
Output: This code is running in a thread

2.Creating thread by extending Thread class

⦿ This is another way to create a thread by a new class that extends Thread class.
Example:
class A extends Thread
{
public void run()
{
System.out.println(“thread started running..");}
}
Class MyThreadDemo{
public static void main( String args[] ) {
A obj = new A();
obj.start();
}
}

Output : concurrent thread started running..

THREAD METHODS

Method Description

start() It is used to start the execution of the thread.

run() It is used to do an action for a thread.

sleep() It sleeps a thread for the specified amount of


time.

It returns a reference to the currently


currentThread() executing thread object.

setPriority() It changes the priority of the thread.

getPriority() It returns the priority of the thread.


isAlive() It tests if the thread is alive.

getId() It returns the id of the thread.

suspend() It is used to suspend the thread.

resume() It is used to resume the suspended thread.

stop() It is used to stop the thread.

destroy() It is used to destroy the thread group and all


of its subgroups.

interrupt() It interrupts the thread.

notify() It is used to give the notification for only one


thread which is waiting for a particular
object.

notifyAll() It is used to give the notification to all


waiting threads of a particular object.

getState() It returns the state of the thread.

It returns the name of the thread.


getName()

EXAMPLE:
class A extends Thread{
public void run() {
for(int i=1;i<=5;i++) {
if(i==2)
yield();
System.out.println("i=”+i); }
}
}
class B extends Thread{
public void run() {
for(int j=1;j<=5;j++) {
System.out.println("from thread B:j="+j);
if(j==3)
stop();
System.out.println("b="+b);
}
}
}
class C extends Thread{
public void run() {
for(int k=1;k<=5;k++) {
if(k==3)
try {
sleep(1000);
}
catch(Exception e) {
System.out.println("caught");
}
}
}
public class ThreadEx{
public static void main(String args[]) {
A a1=new A(); //creating threads
B b1=new B();
C c1=new C();
a1.start();
b1.start();
b1.suspend();
System.out.println("B suspended");
c1.start();
b1.resume();
}
}
THREAD PRIORITY
⦿ In java,each thread is assigned with a priority which affects the order of their
execution.

⦿ In java setPriority() method will be used to set the priority of a thread and
getPriority() is used to get the priority of any thread

Syntax: ThreadName.setPriority(intNumber);
⦿ Priority value can be set between 1 to 10.

⦿ The Thread class defines several priority constants.Those are:

MIN_PRIORITY=1

NORM_PRIORITY=5

MAX_PRIORITY=10

Ex: a.setPriority(MIN_PRIORITY)
Example
class A extends Thread{
public void run() {
for(int i=1;i<=5;i++)
System.out.println("i=”+i);
}
}
class B extends Thread{
public void run() {
for(int j=1;j<=5;j++)
System.out.println("i=”+i);
}
}

publi class Prior


public static void main(String args[]){
TestPriority m1=new TestPriority();
TestPriority m2=new TestPriority();
System.out.println(a1.getPriority());
System.out.println(b1.getPriority());
a1.setPriority(Thread.MIN_PRIORITY);
b1.setPriority(8);
System.out.println(a1.getPriority());
System.out.println(b1.getPriority());
a1.start();
b1.start();
}
}

SYNCHRONIZATION
⦿ Synchronization in java is the capability to control the access of multiple threads to
any shared resource.
⦿ When multiple threads are competing for same resources then they may lead to
serious problems.For Example,if thread t1 is trying to read a record from file while
another thread t2 is writing the same file then thread t1 may read wrong data.This
problem can be eliminated by using synchronization technique in java.

⦿ By using synchronization, problem discussed in above example can be


solved.i.e.when thread t1 acquires a file (shared resource)for read operation then that
file will be locked so that no other threads can access the same file for some other
operation at same time until lock is released by thread t1.

EXAMPLE WITHOUT SYNCHRONIZATION


class Table{
void printTable(int n){ //method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e)
{
System.out.println(e);
}
}
}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}

class MyThread2 extends Thread{


Table t;
MyThread2(Table t){
this.t=t;
}
public void run()
{
t.printTable(100);
}
}

class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

OUTPUT:
5
100
15
200
20
300
20
400
25
500
EXAMPLE WITH SYNCHRONIZATION
class Table{
synchronized void printTable(int n){ //method synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e)
{
System.out.println(e);
}
}
}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}

class MyThread2 extends Thread{


Table t;
MyThread2(Table t){
this.t=t;
}
public void run()
{
t.printTable(100);
}
}

class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
OUTPUT:
5
10
15
20
25
100
200
300
400
500

You might also like