4.exception Handling and Multithreading
4.exception Handling and Multithreading
1.Syntax Errors
--Syntax error refer to the grammatical errors
while writing the code of program.
--Examples are:
1.Misspelled variable and Function names.
2.Missing semicolons;
3.Improperly matching parentheses,square
brackets,and curly braces.
4.Incorrect format in selection and loop
statement.
2.Runtime Error
--Runtime error occur when a program with no syntax error asks the computer
to do something that the computer is unable to reliably.
--These errors occur in the run mode of a program.
--Examples:
1.Trying to divide by a variable that contains value zero.
2.Trying to open a file that does’nt exist.
3.Logical Error
--Logical errors occurs when there is something wrong in the logic of
program.
--Examples:
1.Multitasking when you should be dividing.
2.Adding when you should be subtracting.
3.Opening and using data from the wrong file.
4.Displaying the wrong message
Advantage of Exception Handling
• The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application;
that is why we need to handle exceptions.
• statement 1;
• statement 2;
• statement 3;
• statement 4;
• statement 5;//exception occurs
• statement 6;
• statement 7;
• statement 8;
• statement 9;
• statement 10;
Suppose there are 10 statements in a Java program and an exception occurs at
statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will
not be executed. However, when we perform exception handling, the rest of the
statements will be executed. That is why we use exception handling in Java.
Exception Classes-Subclasses
--All exception classes are considered as the subtype of the java.lang.Exception classes.
--The class is extended from the Throwable class.
--With Exception,one or more class is present named Error which is extended from the Throwable class.
--Errors are unusual situations which occur in case of several failures,which are not handled by the java
programs.
--The Exception class has two main subclasses
:IOException class and RuntimeExceptionclass.
--Hierarchy of exception classes:
Object
Throwable
res=a+b;
System.out.println(“Adddition is:”+res);
}
}
--In this program Addition and division are two tasks,If user input is correct ,then it will produce proper output:
--Suppose user enter 10 and 5 then the output will be 15 and 2.but if user input second number as 0,it will
show error 10 and 0.Then error occur because division by zero is not allowed.
--But the important point is that there is no concern of second number as zero with next task of addition,but still
it does not execute because the program is terminated from the point where the error occurs.
--Now to handle this we have to use try and catch block.
Example:
--Accept two numbers as command line arguments and print the result of division and addition.Throw an
exception if user enters second number as zero.
class Exception
{
public static void main(String [] args)
{
int a=0,b=0,res;
try
{
a=a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
res=a/b;
System.out.println("Division is:"+res);
}
catch(ArithmeticException e)
{
System.out.println("Can not divide by zero:");
}
res=a+b;
System.out.println("Addition is:"+res);
}
}
--Here we can observe that when user enters second number as 0,then the programmer written error message is
displayed and most important factor is that the program is continued and the second task is executed.
--The divide by zero is associated with the ArithmeticException class of java,hence we have to create object for it in
catch block.
Nested try Statement
--Writing a try catch inside another try block is called as nested try block.
--when an exception occurs in inner try then matching inner catch is searched.
--if not found then the exception is transferred to outer catch.
--if the outer catch is also not able to handle it,then it will be handled by java runtime system.
Syntax:
try
{
try
{
----------
----------
}
catch()
{
----------
}
catch(---------)
{
------------
}
class NestedTry
{
public static void main(String[]
args)
{
int a,b,div;
try
{
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
div=a/b;
System.out.println("Division
is:"+div);
}
catch(ArithmeticException e)
{
System.out.println("Cannot divide
by zero");
}
catch
(ArrayIndexOutOfBoundsException e)
{
System.out.println("Insufficient arguments:");
}
}
}
OUTPUT
1.5 0 =>can not divide by zero
2.5 =>Insufficient arguments
--In this example when second argument is passed as 0,then the arithmetic exception
occurs and caught by inner and handled.
--But when second argument is not passed,then ArrayIndexOutOfBoundsException
occur which can not caught by inner catch.Hence it is transferred to outer catch
which caught and handle it.
Multiple catch Blocks
--To handle multiple exception we have to create multiple catch blocks.
class MultiCatch
{
public static void main(String[]args)
{
int a=0,b=0,res;
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
res=a/b;
System.out.println("Divide by zero:"+res);
}
catch(ArithmeticException e)
{
System.out.println("Cannot Divide by zero:");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Insufficient arguments:");
}
catch(NumberFormatException e)
{
System.out.println("Invalid arguments:");
}
res=a+b;
System.out.println("Addition is:"+res);
}
}
Finally
args)
{
int a=0,b=0,res;
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
res=a/b;
System.out.println("Division is:"+res);
}
catch(ArithmeticException e)
{
System.out.println("can not divide by zero");
}
catch
(ArrayIndexOutOfBoundsExceptio
n e)
{
System.out.println("Insufficient
arguments:");
}
finally
{
res=a+b;
System.out.println("Addition
is:"+res);
}
}
}
OUTPUT:
10 5=>Division :2
Addition=>15
10 “ABC”
Addition =>10
--Now in the output we can observe that when second argument is given as string then exception occurs and program is
terminated but still in this case the code written in finally block is executed and result of addition is displayed.
Throws statement/Declaring Exception
--throws keyword is used when we doesn’t want to handle the exception and try to
send the exception to JVM or other method.
--In a program if there is chance of raising an exception then compiler always warn us
about it and we should compulsorily handle that checked exception,otherwise we
will get compile time error saying unreported exception Exception_Name must be
caught or declared to be thrown.
--to prevent this compile time error we can handle the exception in two ways:
1.By using try catch
2.By using throws keyword.
--we can use throws keyword to delegate the responsibilities of exception handling to
the caller (It may be method or the JVM)then caller method is responsible to
handle the exception.
Syntax:
• return_type method_name() throws exception_class_name{
• //method code
• }
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a float Value:");
float n=Float.parseFloat(br.readLine());
if(n<94)
throw new tempException("Tempreature below normal:");
else if(n>=95 && n<100)
throw new tempException("Normal Tempreature:");
else if(n>100)
throw new tempException("High Tempreature:");
}
catch(tempException e)
{
System.out.println(e);
}
}
}
import java.io.*;
import java.lang.Exception;
class AuthenticationFailure extends Exception
{
public AuthenticationFailure()
{
System.out.println("Invalid Password:");
}
}
class ThrowEx3
{
public static void main(String[]args)throws IOException
{
try
{
String pass;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter password:");
pass=br.readLine();
if(pass.equals("rose"))
System.out.println("Login Successfully");
else
throw new AuthenticationFailure();
}
catch(AuthenticationFailure e)
{
System.out.println(e);
}
}
}
import java.io.*;
import java.lang.Exception;
class checkemail extends Exception
{
public checkemail()
{
System.out.println("Exception occurs:");
}
}
class ThrowsEx15
{
public static void main(String[]args)throws IOException
{
if(itemprice>9999)
throw new OverPriceException();
else
System.out.println(itemcode + " " + itemname + " " + itemprice +" ");
}
catch(OverPriceException e)
{
System.out.println(e);
}
}
}
import java.io.*;
import java.lang.Exception;
class InvalidLogin extends Exception
{
public InvalidLogin()
{
System.out.println("Invalid Login");
}
}
class ThreadEx10
{
public static void main(String args[]) throws IOException
{
try
{
String user,pass;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter user name:");
user=br.readLine();
System.out.print("Enter Password:");
pass=br.readLine();
if(user.equals(pass))
System.out.println("Login Successfully:");
else
throw new InvalidLogin();
}
catch(InvalidLogin e)
{
System.out.println(e);
}
}
}
Difference Between Throw and Throws
Parameter Throw Throws
Use It is used to explicitly throw It is used to declare an
an exception exception.
Checked Exception Checked exception cannot Checked exception can be
be implemented using implemented using throws.
throw only.
yield()
Runnable Running
Blocked stop()
--Thread is lightweight sub-process,the smallest unit of processing.
New
--Whenever a new thread is created, it is always in the new state. For a thread in the
new state, the code has not been run yet and thus has not begun its execution.
--it remains in this state until the program starts the thread using its start () method.
Syntax::
public static final Thread.State NEW
--When a thread invokes the start() method, it moves from the new state to the active
state. The active state contains two states within it: one is runnable, and the other
is running.
Runnable
--A thread, that is ready to run is then moved to the runnable state. In the runnable state,
the thread may be running or may be ready to run at any given instant of time. It is the
duty of the thread scheduler to provide the thread time to run, i.e., moving the thread
the running state.
--A program implementing multithreading acquires a fixed slice of time to each individual
thread. Each and every thread runs for a short span of time and when that allocated
time slice is over, the thread voluntarily gives up the CPU to the other thread, so that
the other threads can also run for their slice of time. Whenever such a scenario occurs,
all those threads that are willing to run, waiting for their turn to run, lie in the runnable
state. In the runnable state, there is a queue where the threads lie.
--public static final Thread.State RUNNABLE
--It represents the runnable state.It means a
thread is waiting in the queue to run.
Running state
--In most operating system,each thread is given a
small amount if processor time called a
quantumnor slice to perform its task.
--A thread utilizing its quantum is said to be in
RUNNING state.When its quantum expires,the
thread returns to RUNNABLE state,and the
Operating System assigns another thread to the
processor.
Blocked/Waiting
--A thread enters a waiting state in three
situations:
1.When a thread has called wait() method on
itself and is waiting for other thread to notify
it or wake up.
2.When a thread code has called sleep() method
on a thread asking it to sleep for duration.
3.When a thread is waiting for an Input/Output
resources to be free.
Dead State
--This is considered as last state in thread’s lifecycle.
--A thread enters the dead state after it has successfully
completed executing the run() method.
--At this situation it is considered to be not alive and hence it
cannot be restarted again.
Main Thread
--when execution of java program begins,one thread starts
executing immediately.it is known as the main thread of
program.
--The main thread is important for two reasons:
1)Support child threads
2)Usually it will be last thread to finish execution because it
has to perform several shutdown actions.
--Even though the main thread is created
automatically,to handle it have to create a
Thread Object.for this purpose we must obtain
a reference it to by calling the methid
currentThread(),which is public static member
of thread.
--static Thread currentThread()
--this method returns a reference to the thread
in which it is called.
class ThreadEx1
{
public static void main(String[]args)
{
Thread t=Thread.currentThread();
System.out.println("Current Thread:"+t);
t.setName("My Thread:");
System.out.println("After Name changed:"+t);
try
{
for(int n=5;n>0;n--)
{
System.out.println("\t"+n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread Interrupted:");
}
}
}
Creating Thread
• As we have seen ,By default java provides a ready main thread.But want to
create our own threads then there are two options:
1.By implementing Runnable Interface
2.By extending Thread Class
1.By implementing Runnable Interface
--This is simple option to create Thread.
--Runnable Interface has declared an abstract method run(),which we have to
override(define)in the child class.
--The code of run() method is considered as code of thread.
--The run() method can call other methods ,use other classes and declare
variables,just like main thread can .
--after implementing runnable by a class we can instantiate an object of type
Thread.
class Demo implements Runnable
{
Thread th;
Demo()
{
th=new Thread(this,"Demo");
System.out.println("Chid Thread:"+th);
th.start();
}
public void run()
{
try
{
for(int n=5;n>0;n--)
{
System.out.println("\t Child thread:"+n);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("child Thread interrupted");
}
System.out.println("child Execution completed:");
}
}
class ThreadEx2
{
public static void main(String []args)
{
new Demo();
try
{
for(int n=15;n>10;n--)
{
System.out.println("Main Thread:"+n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Error.......interrupted:");
}
System.out.println("Main Thread Execution Completed");
}
}
BY implementing Extending Thread class
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
class threadEx6
{
public static void main(String args[])
{
class1 target=new class1();
class2 ob1=new class2(target,"Hello");
Rsrc-A
Thread-2 Thread-1
Asrc-A
import java.io.*;
import java.lang.Exception;