`
The try-catch
block in Java is used to handle exceptions and prevent the program from crashing due to runtime errors.
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} finally {
// Code that will always execute (optional)
}
try
Block: Contains code that might throw exceptions.catch
Block: Contains code to handle specific exceptions.finally
Block: Optional; always executes whether or not an exception is thrown.public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
Output:
Cannot divide by zero: / by zero
Finally block executed.
Java provides a robust mechanism for exception handling to deal with runtime errors.
Throwable
: The superclass of all errors and exceptions.
Error
: Critical system errors (e.g., OutOfMemoryError
).Exception
: Recoverable exceptions.
IOException
, SQLException
).NullPointerException
, ArithmeticException
).try
: To define a block of code that might throw an exception.catch
: To handle exceptions.finally
: To execute cleanup code.throw
: To explicitly throw an exception.throws
: To declare exceptions in the method signature.import java.io.*;
public class ExceptionHandlingExample {
public static void readFile(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
System.out.println(br.readLine());
}
public static void main(String[] args) {
try {
readFile("nonexistent.txt");
} catch (IOException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
You can create your own custom exceptions by extending the RuntimeException
class.
class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}
}
public class CustomRuntimeExceptionExample {
public static void checkAge(int age) {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older.");
}
System.out.println("Valid age.");
}
public static void main(String[] args) {
try {
checkAge(16); // Will throw an exception
} catch (InvalidAgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Output:
Exception caught: Age must be 18 or older.
HTTP status codes are used in Java when working with web applications or REST APIs to represent the result of an HTTP request.
Code | Meaning | Description |
---|---|---|
200 | OK | Request was successful. |
201 | Created | Resource was successfully created. |
400 | Bad Request | Request is invalid or cannot be processed. |
401 | Unauthorized | Authentication is required. |
403 | Forbidden | Access to the resource is forbidden. |
404 | Not Found | Resource not found. |
500 | Internal Server Error | Server encountered an error. |
503 | Service Unavailable | Server is temporarily unavailable. |