Java Interview Questions
Java
Web DevelopmentBackendQuestion 24
What is an exception in Java?
Answer:
In Java, an exception is an event that disrupts the normal flow of the program's execution. It is an object that is thrown at runtime by the Java Virtual Machine (JVM) or manually by the code to signal that an error or other unexpected condition has occurred. Exceptions are used to handle errors and other exceptional events in a controlled and predictable manner.
Types of Exceptions
Java categorizes exceptions into three main types:
- Checked Exceptions
- Unchecked Exceptions
- Errors
1. Checked Exceptions
Checked exceptions are exceptions that must be either caught or declared in the method's throws
clause. They are checked at compile-time.
Examples:
IOException
SQLException
ClassNotFoundException
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
File file = new File("nonexistentfile.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
2. Unchecked Exceptions
Unchecked exceptions are exceptions that are not checked at compile-time. They are also known as runtime exceptions. These exceptions are subclasses of RuntimeException
.
Examples:
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
Example:
public class UncheckedExceptionExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
}
}
}
3. Errors
Errors are serious issues that usually indicate problems with the JVM or the environment in which the application is running. They are not meant to be caught or handled by the application.
Examples:
OutOfMemoryError
StackOverflowError
VirtualMachineError
Example:
public class ErrorExample {
public static void main(String[] args) {
try {
causeStackOverflow();
} catch (StackOverflowError e) {
System.out.println("Stack overflow error: " + e.getMessage());
}
}
public static void causeStackOverflow() {
causeStackOverflow();
}
}
Exception Handling
Java provides a robust mechanism for handling exceptions using the try
, catch
, finally
, and throw
keywords.
1. Try-Catch Block
Syntax:
try {
// code that may throw an exception
} catch (ExceptionType1 e1) {
// handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// handle exception of type ExceptionType2
} finally {
// code that will always execute
}
Example:
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
} finally {
System.out.println("This block is always executed.");
}
}
}
2. Throwing Exceptions
You can throw exceptions manually using the throw
keyword.
Example:
public class ThrowExceptionExample {
public static void main(String[] args) {
try {
validateAge(15);
} catch (IllegalArgumentException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
public static void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be at least 18");
}
System.out.println("Valid age: " + age);
}
}
Custom Exceptions
You can create your own exceptions by extending the Exception
class (for checked exceptions) or the RuntimeException
class (for unchecked exceptions).
Example:
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
validateNumber(-5);
} catch (CustomException e) {
System.out.println("CustomException caught: " + e.getMessage());
}
}
public static void validateNumber(int number) throws CustomException {
if (number < 0) {
throw new CustomException("Number must be non-negative");
}
System.out.println("Valid number: " + number);
}
}
Conclusion
Exceptions in Java provide a powerful way to handle errors and other exceptional conditions in a controlled and predictable manner. By understanding and using checked exceptions, unchecked exceptions, and errors appropriately, you can write robust and maintainable Java code. The use of try
, catch
, finally
, and throw
allows you to manage exceptions effectively, ensuring that your application can gracefully handle unexpected situations.