π What is an Exception?
An exception is an unwanted or unexpected event that occurs during the execution of a program and disrupts its normal flow.
π Common Examples:
Dividing a number by zero
Accessing a null object
Trying to open a file that doesnβt exist
- try Block
The try block is used to wrap code that might throw an exception.
Syntax:
try {
// risky code
}
Example:
try {
int a = 10 / 0; // Exception occurs
}
Where is it used?
Database operations
File handling
Network calls
- catch Block
The catch block handles the exception thrown inside the try block.
Syntax:
catch(Exception e) {
// handling code
}
Example:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Where is it used?
Displaying user-friendly error messages
Preventing program crashes
- finally Block
The finally block always executes, whether an exception occurs or not.
Syntax:
finally {
// cleanup code
}
Example:
try {
int a = 10 / 2;
} catch (Exception e) {
System.out.println("Error");
} finally {
System.out.println("Always executed");
}
Real-Time Usage:
Closing database connections
Closing files
Releasing system resources
- throw Keyword
The throw keyword is used to manually throw an exception.
Syntax:
throw new Exception("message");
Example:
public class Main {
public static void main(String[] args) {
int num = -5;
if (num < 0) {
throw new ArithmeticException("Negative number not allowed");
}
System.out.println("Valid number");
}
}
Where is it used?
Custom validations
Business rules (e.g., age restrictions)
- throws Keyword
The throws keyword is used in method signatures to declare exceptions.
Syntax:
void method() throws Exception {
// code
}
Example:
import java.io.*;
class Test {
void readFile() throws IOException {
FileReader file = new FileReader("test.txt");
}
}
Where is it used?
File handling
Checked exceptions
Passing responsibility to the caller
** Conclusion**
Exception handling in Java helps you build robust and error-free applications. By using try, catch, finally, throw, and throws, you can manage errors effectively and ensure smooth program execution.
Top comments (0)