JAVA unit 4
JAVA unit 4
12 Marks
BY : Abhijeet Sir
Contents:
4.1 Errors & Exception-Types of errors, exceptions, try
& catch statement, nested try statement, throws &
Finally statement, build-in exceptions, chained
exceptions, creating own exception subclasses.
Syntax:
finally
{
// block of code to be executed before try block ends
}
When an exception occurr but not handled by the catch
block
try {
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
4) throw:
This keyword is generally used in case of user defined exception,
to forcefully raise the exception and take the required action.
The general form of throw is :
throw new ThrowableInstance;
or
throw Throwableinstance;
throw statement explicitly throws an built-in /user- defined
exception.
Division by Zero
1) Throwable(Throwable cause):
The parameter cause specifies the actual cause of
exception
2) Throwable(String str, Throwable cause):
The string str specifies exception description and cause
specifies the actual cause of exception.
Two methods of Throwable class that supports the chained
exception.
1) Throwable gtCause( ):
This method returns the actual cause of the currently
generated exception.
2) Throwable initCause( ):
This method sets the fundamental exception with invoking
exception.
Example :-
The following java program shows that the program
generates Arithmetic Exception which in turn generates
Number Format Exception.
class Demo
{
public static void main(String args[])
{
int n=10, result=0;
try
{
System.out.println(“The result is”+result);
}
catch(ArithmeticException ex)
{
System.out.println(“Arithmetic exception occoured:”+ex);
try
{
throw new NumberFormatException( );
}
catch(NumberFormatException ex1 )
{
System.out.println(“Chained exception thrown manually:”+ex1)
}
}
}
}
Output
Arithmetic exception occurred:
Java.lang.ArithmeticException:/ by zero
Chained exception thrown manually
Java.lang.NumberFormatException
1.5 Creating own Exception Subclasses
If we want to create our own exception types to handle
situations specific to our applications.
import java.io.*;
class Negative extends Exception
{
Negative(String msg)
{
super(msg);
}
}
class NegativeDemo
{
public static void main(String args[])
{
int age=0;
String name;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter age and name of person");
try
{
age=Integer.parseInt(br.readLine());
name=br.readLine();
{
if(age<0)
throw new Negative("age is negative");
else
throw new Negative("age is positive");
}
}
catch(Negative n)
{
System.out.println(n);
}
catch(Exception e)
{
}
}
}
Now, let's discuss the possible scenarios and the
corresponding output:
Output:
Custom Exception: Age is negative
scenarios 2)
If the user enters a positive age:
Input: Age = 25, Name = Ritesh
Output:
Custom Exception: Age is positive
scenarios 3)
if the user enters a non-integer value for age:
Input: Age = abc, Name = Ritesh
Output:
Other Exception occurred: For input string: "abc"
scenarios 4)
If the user enters a valid integer but doesn't provide
the name:
Input: Age = 30, Name = [Press Enter]
Output:
Other Exception occurred: Stream closed
IOException
2. Write a program to accept password from user and
throw ‘Authentication failure’ exception if password
is incorrect
import java.io.*;
class PasswordException extends Exception
{
PasswordException(String msg)
{
super(msg);
}
}
class PassCheck
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter Password : ");
if(br.readLine().equals(“JAVA"))
{
System.out.println("Authenticated ");
}
else
{
throw new PasswordException("Authentication failure");
}
}
catch(PasswordException e)
{
System.out.println(e);
}
catch(IOException e)
{
System.out.println(e);
}
}
}
Output:
If the user enters the correct password ("JAVA"):
A process is heavyweight.
A thread is lightweight.
Define a class that extends Thread class and override its run()
method.
If all threads have equal priority then they are given time
slots for execution in round robin fashion.
The thread that leave control joins the queue at the end
and again waits for its turn.
2) resume()
syntax : public void resume()
This method resumes a thread which was suspended using
suspend() method.
3) yield()
syntax : public static void yield()
The yield() method causes the currently executing thread
object to temporarily pause and allow other threads to
execute.
4) wait()
syntax : public final void wait()
This method causes the current thread to wait until another
thread invokes the notify() method or the notifyAll() method
for this object.
2.6 Thread Exception
Mostly call to sleep() method is enclosed within a try block
and followed by catch block. This is because the sleep()
method threads an exception, which must be caught.
1. catch(ThreadDeath e)
{
-------- //Killed thread
}
2. catch(InterruptedException e)
{
-------- //cannot handle it in current state
}
3. catch(IllegalArgumentException e)
{
---------- //Illegal method argument
}
4. catch(Exception e)
{
--------- // any other
}
2.7 Thread priority & methods
Thread Priority:
Threads in java are sub programs of main application program
and share the same memory space.
They are known as light weight threads.
A java program requires at least one thread called as main
thread.
The main thread is actually the main method module which is
designed to create and start other threads in java each thread is
assigned a priority which affects the order in which it is
scheduled for running.
Thread priority is used to decide when to switch from one
running thread to another.
Threads of same priority are given equal treatment by the java
scheduler.
Thread priorities can take value from 1-10. Thread class defines
default
priority constant values as
MIN_PRIORITY = 1
NORM_PRIORITY = 5 (Default Priority)
MAX_PRIORITY = 10
Thread Methods:
1. setPriority:
Syntax:
public void setPriority(int number);
This method is used to assign new priority to the thread.
2. getPriority:
Syntax:
public int getPriority();
Syntax
synchronized returntype methodname()
{
------ //code here is synchronized
}
2.9 Inter thread communication
When a two or more thread exits in an application and
they are communicating each other by exchanging
information, then it is called as inter thread
communication
2.10 Deadlock
When two threads have a circular dependency on a
pair of synchronized objects, then there is deadlock.
When two or more threads are waiting to gain control
of resource.