Unit III Exception
Unit III Exception
1. Exception Handling
Exception is an abnormal condition.
ClassNotFoundException,
IOException,
SQLException,
RemoteException, etc.
to handle the runtime errors
to maintain the normal flow of the
application
2. Error
1) Checked Exception
2) Unchecked Exception
Example:
ArithmeticException(51/0)
NullPointerException(s=null)
ArrayIndexOutOfBoundsException,..
3) Error
Catch:
The "catch" block is used to handle the
exception.
It must be preceded by try block which
means we can't use catch block alone.
It can be followed by a finally block later.
Syntax:
catch(Exception e)
{
// Block of code to handle errors
Finally:
The "finally" block is used to execute the
necessary code of the program.
It is executed whether an exception is
handled or not.
Syntax:
finally(Exception e)
{
// Block of code to handle errors
Throw:
The "throw" keyword is used to throw an
exception.
Example2:
public class Exceptionhandle
{
public static void main(String args[])
{
try
{
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the
code...");
} }
Output:
java.lang.ArithmeticException: / by
zero
rest of the code...
Example3:
public class TryCatchExample
{
public static void main(String[] args)
{
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw
exception
} // handling the array exception
catch(ArrayIndexOutOfBoundsException
e)
{
System.out.println(e);
}
System.out.println("rest of the code");
} }
Output:
java.lang.ArrayIndexOutOfBoundsException:
10
rest of the code
Java Multi-catch block
try{
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");
Output:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Example:
public class NestedTryBlock2
{
public static void main(String args[])
{ // outer (main) try block
try { //inner try block 1
try { // inner try block 2
try {
int arr[] = { 1, 2, 3, 4 };
//printing the array element out
of its bounds
System.out.println(arr[10]);
} // to handles
ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic
exception");
System.out.println(" inner try
block 2");
}
}
// to handle ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic
exception");
System.out.println("inner try block
1");
}
} // to handle
ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException
e4) {
System.out.print(e4);
System.out.println(" outer (main) try
block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main
try-block");
}
} }
Output:
Note:
● Only one object can have a throwable
class or subclass.
● Only one exception can be throw
● It must follow by throwable instance
r=a/b;
System.out.println(a+ "/" +b+ "=" +r);
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: " +
ae.getMessage());
}
System.out.println("End of the program");
}
}
Output:
Enter any two numbers: 45
0
Problem info: Division by zero is not possible
End of the program
Throws Exception
The throws keyword specifies the exceptions that a
method can throw to the default handler and
does not handle itself.
It needs a method to throw an exception
automatically.
Note:
The getMessage() method of Throwable class is
used to return a detailed message of the
Throwable object which can also be null.
One can use this method to get the detail message
of exception as a string value.
Finally Exception
The finally keyword is used to define a block that
must be executed irrespective of exception
occurence.
The basic purpose is to cleanup resources
allocated by try block, such as closing file,
closing database connection, etc.
Note:
Syntax: finally
{ block of codes}
Example:
import java.util.Scanner;
public class ThrowsExample
{
int a,b,r;
Scanner input = new Scanner(System.in);
void division() throws ArithmeticException
{
System.out.print("Enter any two numbers:
");
a = input.nextInt();
b = input.nextInt();
r = a / b;
System.out.println(a+"/"+b +"="+r);
}
public static void main(String[] args)
{
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae)
{
System.out.println("Problem info: " +
ae.getMessage());
}
finally
{
System.out.println("finally block
execute always");
}
System.out.println("End of the
program"); }
}
Output:
Enter any two numbers: 5
0
Problem info: / by zero
finally block execute always
End of the program
Java’s Built-in Exceptions
The Java programming language has several built-
in exception classes that support exception
handling. Every exception class is suitable to
explain certain error situations at run time.
All the built-in exception classes in Java were
defined as a package java.lang.
Built-in Exception
Checked exceptions
1. ClassNotFoundException
2. CloneNotSupportedException
Example:
import java.util.Scanner;
class NotEligibleException extends Exception
{
NotEligibleException(String msg)
{
super(msg);
}
}
class VoterList
{
int age;
VoterList(int age)
{
this.age = age;
}
void checkEligibility()
{
try
{
if(age < 18)
{
throw new NotEligibleException("Error: Not
eligible for vote due to under age.");
}
System.out.println("Congrates! You are eligible for
vote.");
}
catch(NotEligibleException nee)
{
System.out.println(nee.getMessage())
;
}
}
public static void main(String args[])
{
Scanner input = new
Scanner(System.in);
System.out.println("Enter your age in
years: ");
Multithreaded Programming
Process-based Thread-based
multitasking multitasking
It allows the It allows the
computer to run two computer to run two
or more programs or more threads
concurrently concurrently
Process is heavy Thread is a light
weight weight
It requires separate It requires same
address space address space
It cannot access over It can access over
idle time of CPU idle time of CPU
Interprocess Not expensive
communication is
expensive
Thread Life cycle
New state:
When a thread object is created using new, then
the thread is said to be the NEW state. It is also
called Born state.
Example: Thread t=new Thread();
Runnable / Ready
When a thread calls start( ) method, then the
thread is said to be in the Runnable state. This
state is also known as a Ready state.
Example: t.start();
Running
When a thread calls run( ) method, then the
thread is said to be Running.
Blocked / Waiting
A thread in the Running state may move into the
blocked state due to various reasons like sleep( )
method called, wait( ) method called, suspend( )
method called, and join( ) method called, etc.
Example:
Thread.sleep(1000);
wait(1000);
wait();
suspened();
notify();
notifyAll();
resume();
Dead / Terminated
A thread in the Running state may move into the
dead state due to either its execution completed or
the stop( ) method called. The dead state is also
known as the terminated state.
● Thread( )
● Thread( String threadName )
● Thread( Runnable objectName )
● Thread( Runnable objectName, String
threadName )
Example
class SampleThread implements Runnable
{
public void run()
{
System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++)
{
System.out.println("i = " + i);
}
}
}
class My_Thread_Test
{
public static void main(String[] args)
{
SampleThread threadObject = new
SampleThread();
Thread thread = new Thread(threadObject);
System.out.println("Thread about to start...");
thread.start();
}
}
OUTPUT:
Thread about to start...
Thread is under Running...
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i = 10
● Thread( )
● Thread( String threadName )
● Thread( Runnable objectName )
● Thread( Runnable objectName, String threadName )
Return
Method Description Value
sleep( long ) moves the thread to blocked state till the void
specified number of milliseconds.
Example
class SampleThread extends Thread
{
public void run()
{
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " +
Thread.currentThread().getName());
}
}
class My_Thread_Test
{
public static void main(String[] args)
{
SampleThread threadObject1 = new
SampleThread();
SampleThread threadObject2 = new
SampleThread();
threadObject1.setName("first");
threadObject2.setName("second");
threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY
);
threadObject1.start();
threadObject2.start();
}
}
OUTPUT:
Inside SampleThread
Inside SampleThreadCurrent Thread: first
Current Thread: second
Synchronization in Multithreading
Wrapper Classes
A Wrapper class in Java is a class whose object
wraps or contains primitive data types.
It can convert primitive data into
corresponding objects.
When we create an object to a wrapper class, it
contains a field and in this field, it can store
primitive data types.
It can wrap a primitive value into a wrapper
class object.
Need of Wrapper Classes
They convert primitive data types into
objects. Objects are needed if you wish to modify
the arguments passed into a method (because
primitive types are passed by value).
The classes in java.util package handles only
objects and hence wrapper classes help in this
case also.
Data structures in the Collection framework,
such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
An object is needed to support
synchronization in multithreading.
Advantages:-
● Collections allowed only object data.
● On object data we can call multiple
methods compareTo(), equals(), toString()
● Cloning process only objects
● Object data allowed null values.
● Serialization can allow only object data.
1. Autoboxing
The automatic conversion of primitive types to the
object of their corresponding wrapper classes is
known as autoboxing.
For example – conversion of int to Integer, long to
Long, double to Double, etc.
// Java program to demonstrate Autoboxing
import java.util.ArrayList;
class Autoboxing
{
public static void main(String[] args)
{
char ch = 'a';
// Autoboxing- primitive to Character object conversion
Character b = ch;
ArrayList<Integer> al= new
ArrayList<Integer>();
// Autoboxing because ArrayList stores only
objects
al.add(25);
// printing the values from object
System.out.println(al.get(0));
}
}
Output: 25
2. Unboxing
It is just the reverse process of autoboxing.
Automatically converting an object of a wrapper
class to its corresponding primitive type is known
as unboxing.
For example – conversion of Integer to int, Long
to long, Double to double, etc.
// Java program to demonstrate Unboxing
import java.util.ArrayList;
class Unboxing
{
public static void main(String[] args)
{
Character ch = 'a';
// unboxing - Character object to primitive conversion
char a = ch;
ArrayList<Integer> al= new
ArrayList<Integer>();
al.add(24);
// unboxing because get method returns an Integer object
int num = al.get(0);
// printing the values from primitive data types
System.out.println(num);
}
}
Output: 24
Q1. Which of these is a wrapper for data type int?
Integer
Long
Byte
Double
Q2. Which of the following methods is a method of wrapper
Integer for obtaining hash code for the invoking object?
int hash()
int hashcode()
int hashCode()
Integer hashcode()
Q3. Which of these methods is used to obtain the value of
invoking object as long?
long value()
long longValue()
Long longvalue()
Long Longvalue()
Q4. What will be the output of the following Java program?
class Output
{
public static void main(String args[])
{
char a[] = {'a', '5', 'A', ' '};
System.out.print(Character.isDigit(a[0]) + "
");
System.out.print(Character.isWhitespace(a
[3]) + " ");
System.out.print(Character.isUpperCase(a[
2]));
}
}
true false true
false true true
true true false
false false false
Compiler
Runtime
Third-party tools
None
Q7. Choose the right statement which does autoboxing in Java.
Ternary Operator
If-else statements
Loops and Switch
All the above
Q10. What will be the output of the following Java program?
class Output
{
public static void main(String args[])
{
Long i = new Long(256);
System.out.print(i.hashCode());
}
}
256
256.0
256.00
257.00
Answer Key & Solution
Q1 Integer
Q2 int hashCode()
Q3 long longValue()
Q4 false true true
Q5 All the above
Q6 Compiler
Q7 Integer temperature1 = 100;
Q8 Yes
Q9 All the above
Q10 256
EXAMPLE:
Input Format
The first input must be a character
The second input must be a byte value
Output Format
Refer sample output for the format specifications
Sample Input
w
120
Sample Output
Displaying values of Wrapper class objects:
Character object: w
Byte object: 120
Displaying unwrapped values:
char value: w
byte value: 120
try{wait();}
catch(Exception e)
{}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}
}
Output:
going to withdraw…
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed...
MCQ TEST
Q1. The wait(), notify(), and notifyAll( ) methods can be called from?
The thread will immediately release the lock of that particular object and enter
into the waiting state.
Immediately the thread will enter into the waiting state without releasing any
lock.
The thread will release the lock of that object but may not immediately.
The thread will release all acquired locks and immediately enter the waiting
state.
Q3. Below “line-1” is valid or not?
Stack s1 = new Stack();
Stack s2 = new Stack();
synchronized(s2)
{
s1.wait(); // line-1
}
Valid
Invalid
Valid only in Windows OS
None of these
Q4. The wait( ) method throws which of the following Exception?
IllegalMonitorStateException
InterruptedException
It doesn’t throw any exceptions
None of these
Q5. After calling the wait() method thread went to the waiting state, and it will come out
of this waiting state on which events?
ABCD55
ACB55D
ACDB55
ACBD55
Q7. The method wait() is a
static method
non-static method
Q8. Inter-thread communication is all about allowing _________ threads to communicate
with each other.
synchronized
non-synchronized
Q9. What is synchronization in reference to a thread?
It’s a process of handling situations when two or more threads need access to
a shared resource
It’s a process by which many threads are able to access the same shared
resource simultaneously
It’s a process by which a method is able to access many different threads
simultaneously
It’s a method that allows too many threads to access any information they
require
Q10. Mutual exclusive and inter-thread communication are which types of
Synchronization?
Thread Synchronization
Process Synchronization
Object Synchronization
None of the above
Answer Key & Solution
Q1 All Synchronized block/method
Q2 The thread will immediately release the lock of that particular object and enter into the
waiting state.
Q3 Invalid
Q4 InterruptedException
Q5 All of these
Q6 ACDB55
Q7 non-static method
Q8 synchronized
Q9 It’s a process of handling situations when two or more threads need access to a shared
resource
Q10 Thread Synchronization