Throwing Exceptions
In Java, we can throw an exception manually using the throw
keyword. This is typically done when we want to enforce some custom error handling logic.
Syntax
1 |
throw new ExceptionType("Error message"); |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Example { public static void main(String[] args) { try { checkAge(15); } catch (IllegalArgumentException e) { System.out.println("Exception: " + e.getMessage()); } } public static void checkAge(int age) { if (age < 18) { throw new IllegalArgumentException("Age must be 18 or older."); } System.out.println("Age is valid."); } } |
In this example, we throw an IllegalArgumentException
when the age is less than 18.
Handling Exceptions
Java provides a mechanism for handling exceptions using try-catch
blocks. We can also use finally
to execute code that should run regardless of whether an exception was thrown or not.
Syntax
1 2 3 4 5 6 7 |
try { // Code that might throw an exception } catch (ExceptionType e) { // Code to handle the exception } finally { // Code that will always execute (optional) } |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class Example { public static void main(String[] args) { try { int result = divide(10, 0); System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Error: Cannot divide by zero."); } finally { System.out.println("This will always execute."); } } public static int divide(int a, int b) { return a / b; } } |
- The
try
block contains the code that might throw an exception. - The
catch
block handles the exception if one is thrown. - The
finally
block will execute whether or not an exception occurred, making it useful for cleanup tasks (like closing a file or releasing resources).
Throwing Custom Exceptions
We can also create custom exceptions by extending the Exception
class or one of its subclasses. This allows us to define more specific exception types for our program.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); } } public class Example { public static void main(String[] args) { try { checkAge(16); } catch (InvalidAgeException e) { System.out.println("Error: " + e.getMessage()); } } public static void checkAge(int age) throws InvalidAgeException { if (age < 18) { throw new InvalidAgeException("Age must be 18 or older."); } System.out.println("Age is valid."); } } |
In this example, we create a custom exception InvalidAgeException
, which is thrown when the age is under 18.