Java Exceptions

The exceptions in java are problematic events which arises during the execution of code. These run-time errors disrupt the normal flow of the program and terminates it abnormally. So it is recommended to handle these run-time errors properly. Exceptions an occur on many different reasons like invalid data provided, file not found, connection to the database lost, server run out of memory etc.

Handling Exceptions

When an exception occur an object is thrown at run-time which need to be handled properly to continue program flow.

Java Exception Types

Java has three type of exceptions.

Checked Exceptions

An exception which occur during the compilation of program is called compile time exception or checked exception. For example ClassNotFoundException, SQLException, NoSuchFieldException, IOException, EOFException etc.

Unchecked Exceptions

An exception which occur during the execution of program is called run-time exception or unchecked exception. For example ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException, NegativeArraySizeException etc.

Errors

An error is an irrecoverable problem which occur during the execution of program and is beyond the control of programmer or user. For example OutOfMemoryError, VirtualMachineError etc.

Catching Exceptions

In java try and catch keyword are used to catch exceptions. A piece of code which might generate an exception is placed in try block and catch block contains the code which runs if exception occurs. The code which is placed in try and catch blocks is called protected code.

Syntax:

try
{

//Code which might generate exception (protected code)

} catch(ExceptionType ex)
{

//code to be executed if exception occurs

}

Example:

public class JavaExceptionHandling {

public static void main(String args[]){

int r = 0;

try {

r = 6/0;

System.out.println(“End of try block”);

} catch (ArithmeticException ex){

System.out.println(“Java exception: ” + ex);

}

System.out.println(“Out of try catch block”);

}

}

Output:

Java exception: java.lang.ArithmeticException: / by zero
Out of try catch block

Catching Multiple Exceptions

In java multiple catch blocks can be written under try block to catch different exception types.

try
{

//Code which might generate exception (protected code)

} catch(ExceptionType1 ex1)

{

//code to be executed if exception occurs

} catch(ExceptionType2 ex2)

{

//code to be executed if exception occurs

} catch(ExceptionType3 ex3)

{

//code to be executed if exception occurs

}

Example:

public class JavaMultipleCatch{

public static void main(String args[]){

try{

int myList[]=new int[10];

myList[12]=20/4;

}

catch(ArithmeticException e){

System.out.println(“Some arithmetic exception occurred”);

}

catch(ArrayIndexOutOfBoundsException e){

System.out.println(“Some index out of bound exception occurred”);

}

catch(Exception e){

System.out.println(“Some other exception occurred”);

}

System.out.println(“Out of try/catch blocks”);

}

}

Output:

Some index out of bound exception occured
Out of try/catch blocks

 

In latest java versions (SE 7 or above) a single catch block can handle multiple exception types.

catch(SQLException | IOException e) {

//code to be executed if exception occurs

}

The Finally Block

The finally block in java can be optionally written under try block or catch block. The code in finally block will always be executed irrespective of occurrence of an Exception. The finally block can be used to perform cleanup actions like closing BufferedReader, FileInputStream etc.

try
{

//Code which might generate exception (protected code)

} catch(ExceptionType ex)
{

//code to be executed if exception occurs

} finally
{

//Statements will always be executed

}

Java Nested Classes

In java you can write a class inside another class as its member. The class which holds the inner class is called outer class and the class written inside is called nested class. We cannot define a class as private in java but the nested class can be made private.The nested class can access all the members of the outer class including private members so it can be used as a security mechanism.

Syntax

class OuterClass{

//outer class body

class NestedClass{

//nested class body

}

//outer class body

}

Types of Nested Classes

  1. Non-static nested class
    • Inner Class
    • Method-local Inner Class
    • Anonymous Inner Class
  2. Static Nested Class

Inner Class

A class written inside body of another non-static class outside method is called inner class. See the inner class below.

class OuterClass{

private class InnerClass{

public void printHello(){

System.out.println(“I am in inner class”);

}

}

void innerHello(){

InnerClass inner = new InnerClass();

inner.printHello();

}

}

public class JavaNestedClass{

public static void main(String args[]){

OuterClass outer = new OuterClass();

outer.innerHello();

}

}

Method-local Inner Class

A class written inside method of outer class is called method-local inner class. See the method-local inner class example below.

public class JavaNestedClass{

void outerClassMethod(){

//the method-local inner class

class MethodInnerClass{

public void printHello(){

System.out.println(“I am in method-local inner class”);

}

}

//Accessing method-local inner class
MethodInnerClass inner = new MethodInnerClass();

inner.printHello();

}

public static void main(String args[]){

JavaNestedClass outer = new JavaNestedClass();

outer.outerClassMethod();

}

}

Anonymous Inner Class

The anonymous inner class in java is a class written inside body of outer class without class name. The class name is decided by compiler at compile-time. It can be used for extending classes and implementing interfaces.

AnonymousClass inner = new AnonymousClass(){

//anonymous class body

};

Static Nested Class

A class written inside another class as static is called static nested class. See the static nested class example below.

public class JavaNestedClass{

static class NestedClass{

public void printHello(){

System.out.println(“I am in static nested class”);

}

}

public static void main(String args[]){

JavaNestedClass.NestedClass inner = new JavaNestedClass.NestedClass();

inner.printHello();

}

}

Java Method Overloading

Method overloading is a feature which allows a class to have multiple methods with same name but different parameter list. There is difference between overloading and overriding. In overriding the method name, type and parameters should be the same in child class as of parent class but the behavior can be specific to the sub class.

See the below method overloading example

public class JavaOverloading{

// to sum integer values

public static int add(int a, int b) {

return a + b;

}

// to sum double values

public static double add(double a, double b) {

return a + b;

}

public static void main(String[] args) {

int a = 20;
int b = 65;
double c = 21.7;
double d = 12.8;

int sumint = add(a, b);
double sumdbl = add(c, d);
System.out.println(“Adding two integer values”);
System.out.println(“Result = ” + sumint);
System.out.println(“Adding two double values”);
System.out.println(“Result = ” + sumdbl);

}

}

Output

Adding two integer values
Result = 85
Adding two double values
Result = 34.5

Method overloading is also called static polymorphism or compile time binding. There cannot be two methods with same name and same number of parameters (parameter type) even if the return type is different.

Java Inheritance

Inheritance is a mechanism in which one class acquires all the methods and fields of another class for code re-usability. The child class which acquires the properties is called sub class or derived class and the class whose properties are acquired is called super class or base class. The “extends” keyword is used to inherit the properties of a super class in a sub class.

Java Inheritance Systax

class JavaParentClass {

//body of base class (method, fields etc)

}

class JavaSubClass extends JavaParentClass {

//methods and fields from JavaParentClass are inherited.

//body of subclass (method, fields etc)

}

Inheritance Example

class JavaParentClass {

int x = 50;

public void welcomeParent(){

System.out.println(“I am in parent class”);

}

}

class JavaInheritance extends JavaParentClass {

int y = 20;

public void welcomeChild(){

System.out.println(“I am in child class”);

}

public static void main(String args[])
{

JavaInheritance c = new JavaInheritance();
c.welcomeParent();
System.out.println(“Value of x is ” + c.x);
c.welcomeChild();
System.out.println(“Value of y is ” + c.y);

}

}

Output

I am in parent class
Value of x is 50
I am in child class
Value of y is 20

super keyword

It is same as this keyword but it is used to access/invoke the members of super class. It differentiate parent class and child class methods with same names. Also it can be used in sub class to invoke the constructor of parent class.

Example

class JavaParentClass{

public void welcome(){

System.out.println(“I am in super class”);

}

}

public class JavaSuperExample extends JavaParentClass {

public void welcome(){

System.out.println(“I am in child class”);

}

public void display(){

JavaSuperExample obj = new JavaSuperExample();
obj.welcome();

//invoking super class method
super.welcome();

}

public static void main(String args[]){

JavaSuperExample obj = new JavaSuperExample();

obj.display();

}

}

Output

I am in child class
I am in super class

Java Method Overriding

Method overriding is a feature which allow a subclass to rewrite the implementation of a method already provided by the super class. The overriding is used to define a behavior that is specific to the sub class. When a class inherits a method then there is possibility to override the functionality of that method which means it was not marked final in super class.

Method Overriding Example

class Employee{

//defining office timing for all employees

public void OfficeTiming(){

System.out.println(“The office timing is 9am to 5pm”);

}

}

public class CustomerServiceRepresentative extends Employee{

//redefining office timing for customer service representatives

public void OfficeTiming(){

System.out.println(“The office timing is 6am to 2pm”);

}

public static void main(String args[]){

CustomerServiceRepresentative emp_csr = new CustomerServiceRepresentative();

emp_csr.OfficeTiming();

}

}

Output

The office timing is 6am to 2pm

Method Overriding Rules

  • The method name should be exactly the same as of overridden method
  • The method return type should be same or sub type of overridden method’s return type
  • The argument list and type should be exactly same as of overridden method
  • The access level should not be more restrictive than access level of overridden method
  • The method should not be written final