Pages

Exception Handling

Throwable : Throwable is a class that represents all errors and exception which may occur in Java Virtual Machine.
Exception Handling : Exception Handling is a mechanism to handle the run time error.
Exception : Exception is an event that disrupt the normal flow of the program.
Error : An Error indicates serious problem that a reasonable application should not try to catch.
Types of Java Exceptions :
  1. Checked Exception
  2. Unchecked Exception
Checked Exception : The Exceptions that are checked at compile time by the Java Compiler are called Checked Exceptions.
Unchecked Exception : The Exceptions that are checked at run time by the JVM are called Un-Checked Exception.

Rules for Exception Handling with respect to Method Overriding

Rule 1 : If parent-class method doesn’t declare any exception

a. Then child-class overriding-method can declare any type of unchecked exception.

public class ParentClass {
      public void testMethod() {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() throws ArithmeticException {
            System.out.println("Child Class");
      }
}

Note: This is the only possibility.

b. If child-class overriding-method declares checked-exception, then compiler throws compile-time error stating.
CTE – “Exception IOException is not compatible with throws clause in ParentClass.testMethod()”.
public class ParentClass {
      public void testMethod() {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() throws IOException {
            System.out.println("Child Class");
      }
}

c. Then child-class overriding-method can declare no exception in the overriding-method of child-class.
This is very much same as that of overridden-method of parent-class (exactly same method-signature)
public class ParentClass {
      public void testMethod() {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() {
            System.out.println("Child Class");
      }
}

Rule 2 : If parent-class method declares unchecked–exception
a. Then child-class overriding-method can declare any type of unchecked exception. Not necessarily same exception as that of parent-class’ method (only for unchecked exception)
public class ParentClass {
      public void testMethod() throws ArithmeticException {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() throws NullPointerException {
            System.out.println("Child Class");
      }
}

b. If child-class overriding-method declares any checked-exception, then compiler throws compile-time error stating.
CTE – “Exception IOException is not compatible with throws clause in ParentClass.testMethod()”.
public class ParentClass {
      public void testMethod() throws ArithmeticException {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() throws IOException {
            System.out.println("Child Class");
      }
}

c. Then child-class overriding-method can declare no exception in the overriding-method of child-class.
public class ParentClass {
      public void testMethod() throws ArithmeticException {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() {
            System.out.println("Child Class");
      }
}

Rule 3 : If parent-class method declares checked exception
a. Then child-class overriding-method can declare any type of unchecked exception.
public class ParentClass {
      public void testMethod() throws IOException {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() throws ArithmeticException {
            System.out.println("Child Class");
      }
}

b. Then child-class overriding-method can declare same type of checked exception or one of its sub-class or no exception.
public class ParentClass {
      public void testMethod() throws IOException {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() throws IOException {
            System.out.println("Child Class");
      }
}

OR sub-type of declared checked exception.

public class ParentClass {
      public void testMethod() throws IOException {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() throws FileNotFoundException {
            System.out.println("Child Class");
      }
}

c. Then child-class overriding-method can declare no exception in the overriding-method of child-class.
public class ParentClass {
      public void testMethod() throws IOException {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() {
            System.out.println("Child Class");
      }
}

Rule 4 : If parent-class method declares combination of both checked and unchecked exceptions
a. Then child-class overriding-method can declare any type of unchecked exception.
public class ParentClass {
      public void testMethod() throws IOException, ArithmeticException {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() throws NullPointerException {
            System.out.println("Child Class");
      }
}

b. Then child-class overriding-method can declare same type of checked-exception or one of its sub-class or no exception.
public class ParentClass {
      public void testMethod() throws IOException, ArithmeticException {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() throws IOException, FileNotFoundException {
            System.out.println("Child Class");
      }
}

c. Then child-class overriding-method can declare no exception in the overriding-method of child-class.
public class ParentClass {
      public void testMethod() throws IOException, ArithmeticException {
            System.out.println("Parent Class");
      }
}
public class ChildClass extends ParentClass {
      public void testMethod() {
            System.out.println("Child Class");
      }
}


Java Custom Checked Exception


public class InvalidAgeException extends Exception {
      InvalidAgeException(String s) {
            super(s);
      }
}
public class AgeValidation {
      public static void validate(int age) throws InvalidAgeException {
            if(age < 18) {
                  throw new InvalidAgeException("not valid");
            } else {
                  System.out.println("welcome to vote");
            }
      }
      public static void main(String args[]) {
            try {
                  validate(13);
            } catch(Exception m) {
                  System.out.println("Exception occured: " + m);
            }
            System.out.println("Rest of the code...");
      }
}

Output :

Exception occured: InvalidAgeException : not valid
Rest of the code...

Java Custom Checked Exception


public class EmailNotUniqueException extends Exception {
      public EmailNotUniqueException(String message) {
            super(message);
      }
}
public class RegistrationService {
      List registeredEmails = Arrays.asList("abc@gmail.com", "xyz@gmail.com");
      public void validateEmail(String email) throws EmailNotUniqueException {
            if (registeredEmails.contains(email)) {
                  throw new EmailNotUniqueException("Email Already Registered");
            }
      }
}
public class RegistrationServiceClient {
      public static void main(String[] args) {
            RegistrationService service = new RegistrationService();
            try {
                  service.validateEmail("abc@gmail.com");
            } catch (EmailNotUniqueException e) {
                  System.out.println("Rest of the code...");
            }
      }
}

Output :

com.jaladhi.EmailNotUniqueException: Email Already Registered
at com.jaladhi.RegistrationService.validateEmail(RegistrationService.java:12)
at com.jaladhi.RegistrationServiceClient.main(RegistrationServiceClient.java:9)

Java Custom Checked Exception


public class NameNotFoundException extends Exception {
      public NameNotFoundException(String message) {
            super(message);
      }
}
public class CustomerService {
      public Customer findByName(String name) throws NameNotFoundException {
            if ("".equals(name)) {
                  throw new NameNotFoundException("Name is empty!");
            }
            return new Customer(name);
      }
      public static void main(String[] args) {
            CustomerService obj = new CustomerService();
            try {
                  Customer cus = obj.findByName("");
            } catch (NameNotFoundException e) {
                  e.printStackTrace();
            }
      }
}

Output :

com.jaladhi.NameNotFoundException: Name is empty!
at com.jaladhi.CustomerService.findByName(CustomerService.java:10)
at com.jaladhi.CustomerService.main(CustomerService.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Java Custom Unchecked Exception


public class ListTooLargeException extends RuntimeException {
      public ListTooLargeException(String message) {
            super(message);
      }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CustomerService {
      public void analyze(List data) {
            if (data.size() > 50) {
                  throw new ListTooLargeException("List can't exceed 50 items!");
            }
      }
      public static void main(String[] args) {
            CustomerService obj = new CustomerService();
            List data = new ArrayList<>(Collections.nCopies(100, "Jaladhi"));
            obj.analyze(data);
      }
}

Output :

Exception in thread "main" com.jaladhi.ListTooLargeException: List can't exceed 50 items!
at com.jaladhi.CustomerService.analyze(CustomerService.java:25)
at com.jaladhi.CustomerService.main(CustomerService.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Java Custom Unchecked Exception


public class DomainNotValidException extends RuntimeException {
      public DomainNotValidException(String message) {
            super(message);
      }
}
public class RegistrationService {
      public void validateEmail(String email) {
            if (!isDomainValid(email)) {
                  throw new DomainNotValidException("Invalid domain");
            }
      }
}
private boolean isDomainValid(String email) {
      List validDomains = Arrays.asList("gmail.com", "yahoo.com", "outlook.com");
            if (validDomains.contains(email.substring(email.indexOf("@") + 1))) {
                  return true;
            }
            return false;
      }
}
public class RegistrationServiceClient {
      public static void main(String[] args) {
            RegistrationService service = new RegistrationService();
            service.validateEmail("abc@gmail1.com");
      }
}

Output :

Exception in thread "main" com.jaladhi.DomainNotValidException: Invalid domain
at com.jaladhi.RegistrationService.validateEmail(RegistrationService.java:10)
at com.jaladhi.RegistrationServiceClient.main(RegistrationServiceClient.java:7)

Java Custom Unchecked Exception


public enum ErrorCodes {
      VALIDATION_PARSE_ERROR(422);
      private int code;
      ErrorCodes(int code) {
            this.code = code;
      }
      public int getCode() {
            return code;
      }
}
public class InvalidCurrencyDataException extends RuntimeException {
      private Integer errorCode;
      public InvalidCurrencyDataException(String message) {
            super(message);
      }
      public InvalidCurrencyDataException(String message, Throwable cause) {
            super(message, cause);
      }
      public InvalidCurrencyDataException(String message, Throwable cause, ErrorCodes errorCode) {
            super(message, cause);
            this.errorCode = errorCode.getCode();
      }
      public Integer getErrorCode() {
            return errorCode;
      }
}
public class CurrencyService {
      public String convertDollarsToEuros(String value) {
            try {
                  int x = Integer.parseInt(value);
            } catch (NumberFormatException e) {
                  throw new InvalidCurrencyDataException("Invalid data", e, ErrorCodes.VALIDATION_PARSE_ERROR);
            }
            return value;
      }
}
public class CurrencyClient {
      public static void main(String[] args) {
            CurrencyService service = new CurrencyService();
            service.convertDollarsToEuros("asd");
      }
}

Output :

Exception in thread "main" com.jaladhi.InvalidCurrencyDataException: Invalid data
at com.jaladhi.CurrencyService.convertDollarsToEuro(CurrencyService.java:10)
at com.jaladhi.CurrencyClient.main(CurrencyClient.java:8)
Caused by: java.lang.NumberFormatException: For input string: "asd"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at mynotes.custom.unchecked.exception.CurrencyService.convertDollarsToEuro(CurrencyService.java:8)
... 1 more

List of Java Unchecked Runtime Exception


S.No Exception Description
1 ArithmeticException Arithmetic Error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException Array index is out-of-bounds.
3 ArrayStoreException Assignment to an array element of an incompatible type.
4 ClassCastException Invalid cast.
5 IllegalArgumentException Illegal argument used to invoke a method.
6 IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
7 IllegalStateException Environment or application is in incorrect state.
8 IllegalThreadStateException Requested operation not compatible with the current thread state.
9 IndexOutOfBoundsException Some type of index is out-of-bounds.
10 NegativeArraySizeException Array created with a negative size.
11 NullPointerException Invalid use of a null reference.
12 NumberFormatException Invalid conversion of a string to a numeric format.
13 SecurityException Attempt to violate security.
14 StringIndexOutOfBounds Attempt to index outside the bounds of a string.
15 UnsupportedOperationException An unsupported operation was encountered.


List of Java Checked Exception


S.No Exception Description
1 ClassNotFoundException Class not found.
2 CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface.
3 IllegalAccessException Access to a class is denied.
4 InstantiationException Attempt to create an object of an abstract class or interface.
5 InterruptedException One thread has been interrupted by another thread.
6 NoSuchFieldException A requested field does not exist.
7 NoSuchMethodException A requested method does not exist.