Exceptions handling
Custom exception classes
Create your own exception class
Use the exception classes in the API whenever possible. Create custom exception classes if the predefined classes are not sufficient.
How to create your own exception class
- To define a checked exception, inherit the Exception class or any of its subclasses.
- To define an unchecked exception, inherit the RuntimeException class or any of its subclasses.
- By convention, each exception class should contain a default constructor that doesn't accept any arguments and another constructor that accepts a string argument.
Syntax to throw your own exception object
throw new ExceptionClassName(messageString);
When to define your own exceptions
- When a method requires an exception that isn't provided by any of Java's exception types
- When using a built-in Java exception would inappropriately expose details of a method's operation
Code for a user-defined exception class
public class MyDivisionByZeroException extends Exception
{
public MyDivisionByZeroException()
{
super("Cannot divide by zero");
}
public MyDivisionByZeroException(String strMessage)
{
super(strMessage);
}
}
Code for a user-defined exception class
public class ProductDAOException extends Exception
{
public ProductDAOException()
{
}
public ProductDAOException(String message)
{
super(message);
}
}
A method that throws the ProductDAOException
public static Product getProduct(String productCode) throws ProductDAOException { try { Product p = readProduct(productCode); // may throw IOException return p; } catch (IOException e) { throw new ProductDAOException("An IO error occurred while retrieving the product."); } }
Code that catches the ProductDAOException
try { Product p = getProduct("1234"); } catch (ProductDAOException e) { System.out.println(e.getmessage()); }