6.What is Finally Block in Java and When it Executes?
The finally block is an optional block used to execute some important cleanup code. Thus, it gets guaranteed to have the same execution no matter what happens in the try and catch blocks. This mainly becomes handy when closing files, releasing database connections or cleaning up other resources.
Key Characteristics of Finally Block:
Always Executes: Finally block is always executed irrespective of whether an exception is thrown by the try block or not.
Post-Catch Execution: In case an exception is caught, finally block executes after the catch block.
No Exceptions? No Problem! In case no exception is thrown, the finally block will still be executed after the try block.
Real-Life Analogy:
Suppose you threw a party in your house. Whether the party was a boom or a fizzle, when it's over, you must clean up afterwards. The finally block works that way too by cleaning up before exiting.
How It Works:
try {
String message = "Welcome to Java!";
System.out.println(message); // No exception here
} catch (NullPointerException e)
System.out.println("An exception occurred.")
;
} finally {
System.out.println("Final cleanup: Closing resources.");
}
What Does This Do?
The try block runs without any problems printing the message.
No exception is thrown, so the catch block is skipped.
The finally block runs, printing the cleanup message.
7.What is the Role of the throw Keyword in Java?
This keyword is explicitly used to throw an exception in your code. It is a way of telling something that something is wrong and deserves attention. It can be used with the built-in as well as the custom exceptions that can give you total control over where and how you want your exceptions to rise.
Why Do We Use the Keyword throw?
Proactive Error Handling: It will enable the early catching of problems by raising an exception whenever specific conditions are not met.
Customizable Messages: It can provide meaningful messages describing the error.
Clear Program Flow: It is easy to know where and why the error occurred.
Example Scenario:
The throw keyword can be thought of as the car's alarm when its fuel level falls critically. When this occurs, the car immediately alerts you to take the necessary action. The throw keyword throws an execution, thus it solves the problem by halting.
Example Code
public void validateAge(int age){
if (age < 18) {
throw new IllegalArgumentException("You must be at least 18 years old.");
}
System.out.println("Age is valid. Access granted.");
}
What's Going On Here?
If the age is below 18, the program throws an exception with a good detail message.
If age is a value that satisfies the condition the program prints the success message.
8.What's the difference between throws and throw in Java?
Do you recall ever taking a road trip where you saw a "Detour Ahead" sign? That sign did not stop you, but it informed you that you had to be prepared for something that may occur during your journey. In Java, throws and throw are a little like those road signs—one lets others know that something could go wrong, while the other actually triggers the problem.
But what do they mean, and when should you use them?
What Does throws Mean?
So imagine you're driving and a sign pops up saying "Detour Ahead." You're not forced to turn, but it's something you might need to deal with. In Java, it is similar: the throws keyword is used within a method declaration to indicate that that method may throw an exception, and it's up to the caller to deal with it. It's more like giving notice to anyone using your method that something unexpected is going to occur and they'd better be ready.
Example :Suppose every time you try opening a file, which doesn't really exist; there just declares the possibility instead, and throws like that:
public void readFile() throws IOException
{
FileReader reader = new FileReader("MyFile.txt " );
}
The second caller can always be equipped with the block or code he /she knows well on how to solve such a condition with that very particular IOException
What About throw?
Consider driving again. You're driving along and then you hit a pothole. What do you do? You honk your horn, right? You let others know something went wrong so they can be aware. This is similar to the Java throw keyword. If something goes wrong in your code, you use throw to raise an exception and alert the program that there is an issue.
Here's a simple example; suppose you want to check a number if it is positive or not. As soon as a number is known to be negative, you must raise an immediate exception:
public void checkNumber(int num) {
if (num < 0) {
throw new IllegalArgumentException("Negative numbers are not allowed");
}
}
This is where the throw is invoked much like when you honk your horn when you hit that pothole. You are raising the exception manually to let others know there is a problem.
So, What's the Real Difference?
throws : This is used in the method signature to warn others that the method might throw an exception so that they can handle it properly.
throw: This is used inside a method to let others know that the exception may be raised if something goes wrong.
And both knowledge of these make you drive past exceptions in your Java code, just like knowing road signs leads you safely to your destination.
9. What Is a Custom Exception in Java and Why Do You Need One?
Ever been at a point when the standard solution is just not enough? Suppose you work in a bakery. A customer has ordered a cake, but did not specify flavor. A generic "order error" wouldn't be helpful in that case, would it? Likewise, in Java, a user defined exception lets you deal with conditions specific to your application. Let's dive in and see how user defined exceptions can make your code more specific and user-friendly.
What Is A User Defined Exception?
Simply put, a custom exception is one you create to solve a specific problem within your application. You do not use generic exceptions, rather, you design one that suits your requirements. It's like having a custom error message that clearly states what went wrong, rather than a vague "something went wrong" type of message.
For example, in a banking application, if the user attempts to withdraw more than what is available in his account, you would want to throw a customized exception and inform him of exactly what the problem is. You can create your own exception class as follows:
public class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
How Do You Use a Custom Exception?
After defining a custom exception, you can use it in your code to handle specific issues
. For instance, if the withdrawal amount is more than the balance, you throw your custom exception to notify the user:
public void withdraw(double amount) throws InsufficientFundsException {
double balance = 500.00; // Example balance
if (amount > balance) {
throw new InsufficientFundsException("You don’t have enough funds to complete this withdrawal.");
}
}
Why Are Custom Exceptions Important?
It is not very helpful to try to solve an order for a cake with the generic "order error" message. Custom exceptions will help you write clear specific error messages for problems that are unique to your application, which will help identify and address particular issues in your code.
Real World Benefit
Using custom exceptions will give your application clearer communication compared to vague error messages. Instead of vague errors that point to just about anything wrong, you're going to get to know the origin of the root cause of this problem. So, it doesn't only save you from ambiguous error messages; it also provides you with something more user friendly and makes code easier to debug and maintain just like in a bakery's service to improve it over specific customer demands.
10. What Is the Hierarchy of Exceptions in Java and How Are Exceptions Classified?
Java organizes the concept of exception like a family tree, where everything originates at the Throwable class, then splits into two major categories Errors and Exceptions.
Let's break it down into a way that makes sense.
Errors: Treat errors as catastrophic failures things you can't do much about. They are like your computer suddenly running out of power while you are in the middle of something important. Examples include OutOfMemoryError, which occurs when your program doesn't have enough memory to keep going. Errors are serious and typically signal issues beyond the application's control.
Exceptions: These are those problems that are easy to handle by your program.
These are categorized into two:
Checked Exceptions: It is like a pre safety check. You have to handle them before running your code. For example, if you are trying to read a file that may not exist, Java forces you to handle the possibility with a try catch block or a throws declaration.
Common ones are IOException (for file handling problems) and SQLException (for database errors).
Unchecked Exceptions: These are more like the unexpected hiccups caused due to errors in your code, like trying to access an array element that doesn't exist (ArrayIndexOutOfBoundsException) or calling a method on a null object (NullPointerException). They belong to the category of the RuntimeException class, don't need to be declared, and thus not handled explicitly.
There is this simple hierarchy to illustrate it for you:
Throwable
├── Error
└── Exception
├── IOException (checked)
└── RuntimeException (unchecked)
The exception hierarchy of Java makes you realize whether some problem is immediately requiring your attention or if you can prepare to handle it when you are actually writing your program.
11. What is a checked exception in Java? Provide an example.
Imagine planning a trip to a new town. You are sure to read the weather prediction before leaving you don't want to experience an unexpected circumstance. Checked exceptions in Java similarly ensure that they account for situations before your programs run.
A checked exception is something the compiler insists you handle. Such exceptions usually deal with interactions involving external resources such as files or networks, where things don't go as planned. If you don't handle a checked exception, your code won't compile.
Here's an example:
import java.io.FileNotFoundException;
import java.io.FileReader;
public class CheckedExceptionExample {
public void readFile() throws FileNotFoundException {
FileReading file = new FileReader("missing_file.txt"); /* might throw FileNotFoundException */
}
}
What's going on here?
If you try to read a file that does not exist, then the Java compiler warns you that the operation might fail.
There are two ways to handle this: either by catching the exception in a try catch block or by declaring it in the method signature using throws FileNotFoundException.
What I would call checked exceptions are when Java says, "Let's make sure that everything is good to go before we take off." They just help your program run even better when things turn out unexpectedly.
12. What is an Unchecked Exception in Java?
Unchecked exceptions in Java are the kinds of surprises that catch you off guard while your program is running. These aren't flagged by the compiler, so you won't know they are there until they actually happen. They often result from some kind of error in logic such as dividing by zero or using an array index that's out of range or referring to an object that hasn't been initialized.
The exceptions which are not checked are put under the category of RuntimeException class. Although they occur at runtime Java does not want you to handle them explicitly but is very much desirable that you anticipate and thus try to avoid them.
Example
public class UncheckedExceptionExample {
public void divideNumbers(int a, int b) {
System.out.println(a / b); /* Throws ArithmeticException if b is zero */
}
}
In this case, if b is zero, the program will throw an ArithmeticException. To prevent this, you can add a condition to check whether b is zero before performing the division. Think of it like checking for ice on the road before driving it's a small precaution that prevents big problems.
13. How Do RuntimeException and Other Exceptions Differ in Java?
In order to understand the difference, imagine RuntimeExceptions as unforeseen mishaps while other exceptions as foreseeable issues.
RuntimeException: These exceptions are like stepping on a banana peel they're usually just the result of mistakes in your code, perhaps trying to access a null object or divide by zero. They do not have to be declared or caught explicitly which makes them "unchecked."
Other Exceptions: These are like scheduled challenges you can prepare for. For example, if you're opening a file, it might not exist and that's something you can anticipate and handle. These are called "checked exceptions" because the compiler forces you to manage them either with a try catch block or by declaring them with throws.
Here's a quick summary:
RuntimeException examples: NullPointerException, ArithmeticException.
Checked exception examples: IOException, SQLException.
When I write code, RuntimeExceptions inform me that my logic needs to be improved and reapplied. I have checked exceptions reminding me to plan for things outside of my control, such as failing networks or a missing file.
14. What is a NullPointerException and Why Does It Occur?
A NullPointerException is Java’s way of saying, “You’re trying to use something that doesn’t exist.” This error occurs when your code attempts to access an object that hasn’t been initialized yet.
Let me break it down with an example:
public class NullPointerExample {
public void printStringLength(String str) {
System.out.println(str.length()); /* Throws NullPointerException if str is null*/
}
}
If you pass a null value to the printStringLength method the program will crash because it's trying to find the length of something that isn't there.
To avoid this, I make it a habit to check whether an object is null before using it.
For example:
if (str!= null) {
System.out.println(str.length());
}
else {
System.out.println("String is null");
}
It's actually like turning the light switch on in a completely dark room. Before you take the action of turning the light switch on, you ensure there is a bulb to light. Taking such simple precautions prevents your errors but will also make your code more dependable and easier to maintain.
15. What Is an ArithmeticException and How Do I Avoid It in Java?
Java ArithmeticException, that's a mouthful, right? Well, technically speaking, an arithmetic exception is nothing but when math rules are being broken in your program. Most people are familiar with this happening as division by zero. Don't worry, it's not an end in the tunnel. That's just when you have room to make your code more smart and resilient.
Let's illustrate with a super basic example
public class ArithmeticExample{
public void divideNumbers(int x, int y) {
int res = x / y; /* This throws ArithmeticException if x is 0 */
}
}
This type of error can throw your program off, but it's very simple to avoid. With a single check, you can elegantly handle the case where the divisor is zero:
public class ArithmeticExample {
public void divideNumbers(int x, int y) {
if (y != 0) {
int res = x / y;
System.out.println("Result is =: " + res);
}
else {
System.out.println("A Number Division by zero is not allowed!");
}
}
}
Adding this validation means your program stays stable and provides useful feedback rather than crashing. It's a bit like guardrails on a winding road: it keeps things running smoothly and safely, even if someone veers off track. This extra step transforms potential errors into teachable moments, both for your code and its users.
16. What Is an ArrayIndexOutOfBoundsException and How Do You Handle It in Java?
That is, an ArrayIndexOutOfBoundsException is generated whenever an attempt is made to access a position in an array that does not exist. Think of it like reaching into a box anticipating ten items, only to find there are only three you're grabbing at thin air. This exception helps you catch and correct such mishaps in your program.
Here's what might go wrong:
public class ArrayIndexExample {
public void accessArray(){
int[] arr = {11, 21, 13};
System.out.println(arr[5]); /* Throws ArrayIndexOutOfBoundsException */
}
}
You can prevent this error from happening by verifying the index to ensure it's within valid range before trying to access it as well:
public class ArrayIndexExample {
public void accessArray()
int[] arr = {10, 20, 30};
int index = 5;
if (index >= 0 && index < arr.length) {
System.out.println("Value at index " + index + ": " + arr[index]);
}
else {
System.out.println("Invalid index! Request you provide a index value between 0 and " + (arr.length - 1));
}
}
}
This approach does more than prevent crashes it makes your program feel thoughtful and reliable. It's like giving users a helpful signpost when they're about to make a mistake, ensuring they stay on the right path. With this level of attention, your code becomes more than functional it becomes a tool that inspires confidence.
17.What is a ClassNotFoundException in Java, and when does it happen?
Consider looking for a book in the library. If it is not there, the library catalog hasn't included the book. The same thing is essentially what is going on with the ClassNotFoundException in Java. The exception is thrown if Java is attempting to dynamically load a class via methods such as Class.forName(), but Java cannot locate that class within the given classpath.
Here's a very simple example:
public class Loader {
public void loadClass() throws ClassNotFoundException {
Class.forName("com.example.NonExistentClass"); /* Throws ClassNotFoundException */
}
}
Here, Java will look for com.example.NonExistentClass in the project if it exists and is accessible to the runtime classpath. So, the application will fail when it fails to find this in the project.
To avoid that, check you have all the needed classes in proper packages and then referenced them all. I personally had this once when I missed some library dependency when creating a new project. To fix this quick solution was simply adding a JAR file for the missing part to the classpath and, voila - it works nicely!
18. What is IOException in Java? How Do I Handle It?
Have you ever opened the file with your application just to find it not existing, or the issue would be related with the file, itself? If so in Java, those result in IOExceptions. A checked exception you cannot avoid declaring anywhere in the methods where such situation might appear as well, ranging from general failure of input operation to any failing network activity to get it running.
So what can bring one here are:
import java.io.*;
public class IOExceptionExample {
public void readFile() throws IOException {
FileReader file = new FileReader("file.txt"); // Throws IOException if the file doesn't exist
}
}
In this example, if file.txt isn't found or accessible, Java throws an IOException. But don't worry you can handle it with a try-catch block:
public class IOExceptionExample {
public void readFile(){
try {
FileReader file = new FileReader("file.txt");
System.out.println("File read successfully!");
}
catch (IOException e) {
System.out.println("Error: File not found or cannot be read. Please check its location and try again.");
}
}
}
Including meaningful error messages in cases like this feels incredibly rewarding. They make your program user friendly and save you from endless debugging sessions. Imagine building a file processing tool clear error messages will help you understand what was wrong and what to do differently thus greatly improving the entire experience.
Previous Topic==> Best Java OOPS practices FAQ. || Next Topics==> Types of Exceptions in Java FAQ
Other Topic==>
Banking Account Management Case Study in SQL
Top SQL Interview Questions
Employee Salary Management SQL FAQ!. C FAQ
Top 25 PL/SQL Interview Questions
Joins With Group by Having
Equi Join
Joins with Subqueries
Self Join
Outer Join