Page 251 - IT-802_class_12
P. 251
The following code fragment handles a division by zero exception:
try { int quotient = divide(10,0);
System.out.println(quotient); } catch (Exception e)
{
System.out.println(e.getmessage());
}
We catch an exception of the type Exception. An object of the class Exception is a “catch all” exception that returns a
general error message encountered during program execution. The exception handler in the catch block uses the get
Message() method of the Exception class to print the error that caused the exception.
3.10 thrEadS
A multithreaded program is one that can perform multiple tasks concurrently so that there is optimal utilization of the
computer’s resources. A multithreaded program consists of two or more parts called threads each of which can execute
a different task independently at the same time.
In Java, threads can be created in two ways
Ð ÐBy extending the Thread class
Ð ÐBy implementing the Runnable interface
The first method to create a thread is to create a class that extends the Thread class from the java.lang package and
override the run() method. The run() method is the entry point for every new thread that is instantiated from the class.
public class ExtendThread extends Thread
{
public void run()
{
System.out.println(“Created a Thread”);
for (int count = 1; count <= 3; count++)
System.out.println(“Count=”+count);
}
}
To create a thread, instantiate it from the ExtendThread class, and to start its execution, call the start() method of the
Thread class.
Fundamentals of Java Programming 249

