Java IA3 Question Bank_vamshi
Java IA3 Question Bank_vamshi
1. try Block
The try block contains the code that might cause an exception. If an error occurs, the
exception is thrown, and control is transferred to the appropriate catch block.
2. catch Block
The catch block handles the exception thrown by the try block. You can specify different
types of exceptions and provide customized handling for each type.
3. finally Block
The finally block contains code that is always executed, regardless of whether an exception
occurs or not. This is typically used for cleanup actions like closing files, releasing resources,
or closing database connections.
try {
System.out.println("Attempting to withdraw $600...");
account.withdraw(600); // This will throw an InsufficientFundsException
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
}
try {
System.out.println("Attempting to withdraw $300...");
account.withdraw(300); // This will succeed
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionbyZero using try , catch , throw, throws and finally
class DivisionByZeroException extends Exception
{
public DivisionByZeroException(String message)
{
super(message);
}
}
public class CustomExceptionExample
{
public static void main(String[] args)
{
try {
int dividend = 10;
int divisor = 0;
if (divisor == 0)
{
throw new DivisionByZeroException("Division by zero is not allowed");
}
2. getLocalizedMessage()
Purpose: Returns a localized description of the exception/error message.
Use Case: Useful for internationalization (i18n) where error messages need to
be in different languages.
Example:
try {
throw new Exception("File not found");
} catch (Exception e) {
System.out.println("Localized Message: " + e.getLocalizedMessage());
}
Output:
mathematica
Localized Message: File not found
3. printStackTrace()
Purpose: Prints the stack trace of the Throwable to the standard error stream
(or another output stream).
Use Case: To debug and understand where the exception occurred.
Example:
java
Copy code
try {
String str = null;
str.length();
} catch (NullPointerException e) {
e.printStackTrace();
}
Sample Output:
css
Copy code
java.lang.NullPointerException
at Main.main(Main.java:5)
4. toString()
Purpose: Returns a string representation of the Throwable, which includes the
exception's class name and the detail message.
Use Case: Provides a concise description of the exception.
Example:
java
Copy code
try {
int[] numbers = new int[2];
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.toString());
}
Output:
makefile
Copy code
java.lang.ArrayIndexOutOfBoundsException: 5
5. getStackTrace()
Purpose: Returns an array of StackTraceElement objects representing the stack
trace.
Use Case: To programmatically analyze the stack trace.
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
StackTraceElement[] stackTrace = e.getStackTrace();
for (StackTraceElement element : stackTrace) {
System.out.println(element);
}
}
Sample Output:
css
Copy code
Main.main(Main.java:4)
6. setStackTrace(StackTraceElement[] stackTrace)
Purpose: Modifies the stack trace of the Throwable.
Use Case: To manipulate or modify the stack trace before displaying it (useful
in logging or debugging).
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
e.setStackTrace(new StackTraceElement[] {
new StackTraceElement("CustomClass", "customMethod", "CustomFile.java",
123)
});
e.printStackTrace();
}
Output:
csharp
java.lang.ArithmeticException: / by zero
at CustomClass.customMethod(CustomFile.java:123)
7. getCause()
Purpose: Returns the cause of the Throwable, or null if the cause is unknown.
Use Case: To identify the underlying cause of an exception.
Example:
java
try {
throw new RuntimeException("Top-level exception", new
IllegalArgumentException("Cause of the problem"));
} catch (RuntimeException e) {
System.out.println("Cause: " + e.getCause());
}
Output:
makefile
Copy code
Cause: java.lang.IllegalArgumentException: Cause of the problem
8. initCause(Throwable cause)
Purpose: Sets the cause of the Throwable. Used to chain exceptions.
Use Case: To associate a secondary exception as the cause of a primary
exception.
Example:
try {
NullPointerException npe = new NullPointerException("Null pointer occurred");
npe.initCause(new IllegalArgumentException("Invalid argument passed"));
throw npe;
} catch (NullPointerException e) {
System.out.println("Exception: " + e);
System.out.println("Cause: " + e.getCause());
}
Output:
yaml
Copy code
Exception: java.lang.NullPointerException: Null pointer occurred
Cause: java.lang.IllegalArgumentException: Invalid argument passed
9. fillInStackTrace()
Purpose: Reinitializes the stack trace of the Throwable to the current thread's
stack trace.
Use Case: To reset the stack trace to reflect the current execution context.
Example:
try {
throw new Exception("Initial Exception");
} catch (Exception e) {
e.fillInStackTrace();
e.printStackTrace();
}
Differentiate between process and thread.
Aspect Process Thread
A process is an independent A thread is the smallest unit of
execution unit that contains execution within a process.
Definition
its own memory space and Threads within the same
resources. process share resources.
Threads share the same
Memory Each process has its own
memory space within a
Space separate memory space.
process.
Threads can
Inter-process communication
communicate directly by
Communication (IPC) is needed to share data
sharing variables and
between processes.
memory.
Creating a process is expensive Creating a thread is
Creation
and slow due to memory relatively fast and has
Overhead
allocation and OS overhead. low overhead.
Context switching between Context switching between
Context processes is slower due to threads is faster because
Switching separate memory space and threads share the same
resources. memory.
Processes are independent of Threads within the same
Independence each other and can run process are dependent on
separately. each other.
Each process has its own Threads share the process's
Resource
resources, such as file resources but have their own
Allocation
handles and CPU registers. execution stack and registers.
Fault A failure in one process does A failure in one thread can
Isolation not affect other processes. affect the entire process.
Running two separate Downloading a file while playing a video
Example applications (e.g., a web in a media player (multiple threads within
browser and a text editor). one application).
Explain how to create multiple threads using the Thread class with an
example
The easiest way to create a thread is to create a class that implements the Runnable
interface. The Runnable interface abstracts a unit of executable code. You can
construct a thread on any object that implements Runnable.
To implement Runnable, a class only needs to implement a single method called
run().
public void run( )
Inside run(), you will define the code that constitutes the new thread. The run()
method can call other methods, use other classes, and declare variables. The run()
method establishes the entry point for another, concurrent thread of execution
within your program. This thread will end when run() returns.
After you create a class that implements Runnable, you will instantiate an object of
type Thread from within that class. The Thread class defines several constructors.
The constructor shown below takes an instance of a class that implements the
Runnable interface and a string that specifies the name of the new thread.
Thread(Runnable threadOb, String threadName)
After the new thread is created, it will not start running until you call its start()
method, which is declared within the Thread class. The start() method executes a call
to run().
void start( )
Example
class MyThread implements Runnable {
Thread thrd;
class MoreThreads {
public static void main(String args[]) {
System.out.println("Main thread starting.");
try {
for(int count=0; count < 10; count++) {
Thread.sleep(400);
System.out.print(".");
}
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread ending.");
}
}
class MoreThreads {
public static void main(String args[]) {
System.out.println("Main thread starting.");
try {
for(int count=0; count < 10; count++) {
Thread.sleep(400);
System.out.print(".");
}
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread ending.");
}
}
1.
2.
3.
4.
5.
6.
7.
8.
9. Explain the concept of synchronization with example
10. Write a program to illustrate creation of threads using runnable interface .(Using start()
method start each of the newly created thread .Inside the run method there is sleep() for
suspend the thread for 500 milliseconds)
11. Develop a program to create a class MyThread in this class a constructor , call the base class
constructor, using super and start the thread . The run method of the class starts after this. It
can be observed that both main thread and created thread are excecuting concurrently.
12. Explain the exceptions ArrayIndexOutofBoundsException and ArithmeticException.
13. Explain the class hierarchy specific to exception handling.