Java Preparation Unit - 4-1
Java Preparation Unit - 4-1
Unit-4
Exception Handling AND Multithreading
2 Marks
1. Define error. List types of error.
Ans) An error in programming refers to any mistake in the code that prevents it from
executing successfully.
Types of errors in Java include:
• Compile-time errors (Syntax errors): These occur due to violations of the rules
of the programming language, such as missing semicolons, mismatched
parentheses, or incorrect variable names. These errors are detected by the
compiler during the compilation phase and must be fixed before the program can
be executed.
• Runtime errors: These occur during program execution and may lead to
abnormal termination. Runtime errors include exceptions such as
NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException,
and others. These errors occur when the program is running and encountering
unexpected conditions that it cannot handle.
ii) sleep()
Sleep() causes the current thread to suspend execution for a specified period.
Syntax: public static void sleep(long milliseconds)
4. FileNotFoundException: Occurs when attempting to access a file that does not exist.
5. IOException: General I/O exception that occurs during input or output operations.
9. OutOfMemoryError: Occurs when the Java Virtual Machine (JVM) runs out of
memory to allocate new objects.
10. SecurityException: Occurs when an applet tries to perform an operation not allowed
by the security settings.
11. StackOverflowError: Occurs when the call stack exceeds its maximum size due to
infinite recursion or excessive method calls.
1. New:
• A thread enters the new state when it is instantiated but has not yet started its
execution.
• At this stage, the thread is considered alive, but it has not been started yet.
2. Runnable:
• A thread enters the runnable state when the start() method is called on it.
• In this state, the thread is ready to run, but the scheduler has not yet selected it to
be executed.
• The thread scheduler selects threads from the runnable pool and moves them to
the running state based on priority and other factors.
3. Running:
• A thread enters the running state when the scheduler selects it from the runnable
pool for execution.
• In this state, the thread is actively executing its task or code.
• The thread remains in the running state until it completes its task, is preempted
by a higher-priority thread, or voluntarily yields its execution by calling yield()
or sleep() methods.
4. Blocked/Waiting:
• A thread enters the blocked or waiting state when it is temporarily inactive or
waiting for a certain condition to be fulfilled.
• The thread remains in this state until the condition it is waiting for is satisfied, at
which point it moves back to the runnable state.
• Some methods are:
✓ suspend(): Suspends the execution of the current thread until it is resumed
by calling resume()
✓ sleep(long milliseconds): Pauses the execution of the current thread for the
specified number of milliseconds before resuming execution.
✓ wait(): Causes the current thread to wait until another thread invokes the
notify.
✓ resume(): Resumes the execution of a suspended thread that was previously
suspended using suspend().
✓ notify(): Wakes up a single thread that is waiting on the same object by
invoking the wait() method.
5. Terminated:
• A thread enters the terminated state when it completes its task or is explicitly
terminated by calling the stop() method (not recommended) or when the run()
method exits.
• Once a thread is terminated, it cannot be restarted or moved to any other state.
4. Explain exception handling mechanism w.r.t. try, catch, throw and finally.
Ans) ❖ Try:
• The try block encloses the code that might throw an exception.
• It is followed by one or more catch blocks or a finally block.
• The code inside the try block is monitored for exceptions.
Syntax:
try {
// Code that might throw an exception
// This block is monitored for exceptions
}
❖ Catch:
• A catch block follows a try block and is used to handle specific types of
exceptions.
• It catches the exception thrown by the try block and executes the corresponding
code to handle the exception.
• A single try block can have multiple catch blocks to handle different types of
exceptions.
Syntax:
catch (ExceptionType exceptionVariable) {
// Handle the exception
// Code to execute when the specified exception occurs
}
❖ Throw:
• The throw keyword is used to explicitly throw an exception within a method or
block of code.
• It allows you to create and throw custom exceptions or propagate existing ones.
Syntax:
throw new ExceptionType("Error message");
❖ Finally:
• The finally block follows the try and catch blocks (if any).
• It contains code that is always executed, regardless of whether an exception is
thrown or caught.
• The finally block is often used to perform cleanup tasks, such as closing resources
(e.g., files, database connections) or releasing locks.
Syntax:
finally {
// Cleanup code or code that always needs to be executed
}
6 Marks
1. Define thread priority? Write default priority values and the methods to set and
change them.
Ans) Thread Priority:
Thread priority in Java determines the importance of a thread relative to other threads.
Threads with higher priority are given preference in accessing the CPU resources over
threads with lower priority. However, it's important to note that thread priority is only a
suggestion to the thread scheduler and may not be strictly followed by all JVM
implementations.
Default Priority Values:
• The default priority value for a thread is 5.
• Thread priorities range from 1 to 10, where 1 is the lowest priority and 10 is the
highest priority.
Methods to Set and Change Thread Priority:
1. getPriority():
• This method is used to retrieve the current priority of the thread.
• Syntax: int getPriority()
2. setPriority(int priority):
• This method is used to set the priority of the thread.
• Syntax: void setPriority(int priority)
• Note: The priority parameter must be an integer value between 1 and 10
inclusive.
Example:
public class PriorityExample extends Thread {
public void run()
{
System.out.println("Thread name: " + Thread.currentThread().getName() + ",
Priority: " + Thread.currentThread().getPriority());
}
The following methods are used to get and set the priority of a thread:
1. getPriority() Method:
• This method returns the priority of the thread as an integer value.
• Syntax:
public int getPriority()
thread.setPriority(Thread.MAX_PRIORITY);