Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
In Java, exceptions are events that occur during the execution of a program that disrupt its normal flow. Java provides many built-in exception classes, such as NullPointerException
, IOException
, and ArithmeticException
. However, in some cases, you may need to create your own custom exceptions to handle specific situations. In this tutorial, we will cover how to create and use custom exceptions in Java.
To create a custom exception, extend one of the existing exception classes, usually Exception
or RuntimeException
. By convention, custom exception class names should end with "Exception".
Example:
public class CustomException extends Exception { public CustomException(String message) { super(message); } }
In the example above, we created a custom exception called CustomException
that extends the Exception
class. We added a constructor that takes a String
message as a parameter and calls the superclass constructor with the provided message.
To throw a custom exception, use the throw
keyword followed by the new
keyword and the custom exception constructor.
Example:
public class Main { public static void main(String[] args) { try { validateAge(15); } catch (CustomException e) { System.out.println("Caught exception: " + e.getMessage()); } } public static void validateAge(int age) throws CustomException { if (age < 18) { throw new CustomException("Age must be 18 or older"); } } }
In the example above, we created a method called validateAge()
that checks if the provided age is 18 or older. If the age is less than 18, it throws a CustomException
with a custom error message. In the main()
method, we called the validateAge()
method inside a try
block and caught the CustomException
in a catch
block.
Unchecked exceptions are exceptions that extend RuntimeException
. They don't need to be explicitly declared in the method signature with the throws
keyword.
Example:
public class CustomUncheckedException extends RuntimeException { public CustomUncheckedException(String message) { super(message); } }
In this example, we created a custom unchecked exception called CustomUncheckedException
that extends RuntimeException
. We added a constructor that takes a String
message as a parameter and calls the superclass constructor with the provided message.
Throwing a custom unchecked exception is similar to throwing a checked exception, but you don't need to declare it with the throws
keyword in the method signature.
Example:
public class Main { public static void main(String[] args) { try { validateUsername("short"); } catch (CustomUncheckedException e) { System.out.println("Caught exception: " + e.getMessage()); } } public static void validateUsername(String username) { if (username.length() < 6) { throw new CustomUncheckedException("Username must be at least 6 characters"); } } }
In this example, we created a method called validateUsername()
that checks if the provided username is at least 6 characters long. If the username is shorter, it throws a CustomUncheckedException
with a custom error message. In the main()
method, we called the validateUsername()
method inside a try
block and caught the CustomUncheckedException
in a catch
block.
Creating custom exceptions in Java example
Custom exceptions are user-defined exceptions that extend either Exception
(checked) or RuntimeException
(unchecked). Here's an example:
// Custom checked exception public class MyCheckedException extends Exception { public MyCheckedException(String message) { super(message); } } // Custom unchecked exception public class MyUncheckedException extends RuntimeException { public MyUncheckedException(String message) { super(message); } }
Extending RuntimeException for custom exceptions in Java
Extending RuntimeException
creates unchecked exceptions, meaning they don't need to be declared or caught explicitly.
// Custom unchecked exception public class MyUncheckedException extends RuntimeException { public MyUncheckedException(String message) { super(message); } }
Throwing and catching custom exceptions in Java
You can throw and catch custom exceptions like any other exception. Example:
public class Example { public void myMethod() throws MyCheckedException { // Throw custom checked exception throw new MyCheckedException("Custom Checked Exception"); } public static void main(String[] args) { Example example = new Example(); try { // Catch custom checked exception example.myMethod(); } catch (MyCheckedException e) { System.out.println("Caught: " + e.getMessage()); } } }
Defining checked and unchecked custom exceptions
Checked exceptions extend Exception
, and unchecked exceptions extend RuntimeException
. Example:
// Custom checked exception public class MyCheckedException extends Exception { public MyCheckedException(String message) { super(message); } } // Custom unchecked exception public class MyUncheckedException extends RuntimeException { public MyUncheckedException(String message) { super(message); } }
Java custom exception handling strategies
Custom exception handling strategies may include logging, retrying, or providing meaningful error messages to users. Example:
public class Example { public void myMethod() { try { // Code that may throw exceptions } catch (MyCheckedException e) { // Log the exception System.err.println("Exception occurred: " + e.getMessage()); // Retry or take appropriate action // ... } } }
Chaining exceptions with custom exceptions in Java
You can chain exceptions by passing the cause to the constructor of a new exception.
public class ChainedExceptionExample { public void myMethod() { try { // Code that may throw exceptions } catch (Exception cause) { // Wrap the cause in a custom exception throw new MyCheckedException("Custom Checked Exception", cause); } } }
Using custom exceptions in Java applications
Custom exceptions can be used to signal and handle specific error conditions in your applications. Example:
public class FileProcessor { public void processFile(String filePath) throws FileProcessingException { // Process file, throw custom exception if an error occurs if (errorCondition) { throw new FileProcessingException("Error processing file: " + filePath); } } }
Custom exception vs. standard exception in Java
Custom exceptions should be used for application-specific error conditions, while standard exceptions are for general errors. Example:
public class CustomExceptionExample { public void myMethod() throws MyCustomException { // Custom exception for specific error condition if (errorCondition) { throw new MyCustomException("Custom error message"); } // Standard exception for general errors throw new IOException("IO error occurred"); } }