Java – Try, Catch, Finally, Throw, Throws, Exceptions, Assertions


What does exception mean ? (or) what is exception ?

Its a process of excluding a person or a thing , preventing them to follow the general rules.

Its also stated as process of finding and allowing a person or a thing, not to follow the general rules.

What is exception in java ?

Its is a process which occurs during the execution of the program, which disrupts the normal flow of the programming instructions.

If there is an unexpected event/error occurred during the execution of the program during the run time is called as Exceptions.

When an error occurred during the execution of the program, the error is thrown to the runtime system which is resulted as Exceptions.

If an error occurred during the execution the error mechanism will terminate the whole program at that point itself and even the compiler doesn’t know about this error.

Why we need an exception in java ?

Errors are common in all programming language, In order to handle the errors Exception mechanism is used.

The main purpose is to handle the errors effectively and transfer the control of the program from one part to another part.

Difference between error and exception

What is error in java?

Error is a serious problem which affects the whole process of the program.

Error is capable of terminating the program in runtime environment.


Error once occurred cannot be recovered.

Error will occur during the runtime mechanism of the program which is even not known to the compiler.

Error is defined in java.lang.Error package in java.

Examples:

java.lang.StackOverflowError

java.lang.OutOfMemoryError

What is exception in java ?

Java exception can be recovered using try, catch, exception mechanism in Java.

Checked exception in java will be known to the compiler and it can be catched.

Unchecked exception in java is not known to the compiler.

Java exception class are defined in java.lang.Exception package in Java.

Types of exception in java

Checked and Unchecked exception in java

1. Checked exceptions 

Checked Exceptions are checked by the compiler, The compiler checks whether the code can be handled or not and if the compiler is unable to handle it throws the compilation error.

Examples:

SQLException

IOException

FileNotfoundException

2. Unchecked exceptions.

Unchecked Exceptions are not checked by the compiler, even if the exceptions are not handled inside the code the compiler compiles the program successfully.

Examples:

ArrayIndexOutOfBoundException

NullPointerException

ArithmeticException

How Java exceptions are handled ?

Exception handling in java is done by using try, catch, throw, throws and finally keywords.

1. try-catch block

Java keyword try acts as the start of the block and catch keyword acts as the end of the try block for catching exceptions.

Together its called try-catch block for catching exceptions in the program.

Syntax :

try{
//statements...
}
catch(exception-type exception-object){
// statements
}

Exception handling in java with examples.

Example :

public class tryCatchExample{
  public static void main(String args[]){
   try{
      int a = 50;
      int data=a/0;
   }catch(Exception e)
   {
           System.out.println(e);
   }
   System.out.println("code flows to the next steps...");
}
}

Output :

java.lang.ArithmeticException: / by zero

code flows to the next steps…

We can define the exception class name directly

Example :

public class tryCatchExample{
  public static void main(String args[]){
   try{
      int a = 50;
      int data=a/0;
   }catch(ArithmeticException e)
   {
           System.out.println(e);
   }
   System.out.println("code flows to the next steps...");
}
}

Output :

java.lang.ArithmeticException: / by zero

code flows to the next steps…

Declaring multiple catch block

Example :

public class tryCatchExample{
  public static void main(String args[]){
          try{
                  int num = 30;
                  int a[]=new int[10];
                  a[2]=num/0;
                  System.out.println("First print statement in try block");
          }
          catch(ArithmeticException e){
                  System.out.println("Exception Name : ArithmeticException");
          }
          catch(ArrayIndexOutOfBoundsException e){
                  System.out.println("Exception Name : ArrayIndexOutOfBoundsException");
          }
          catch(Exception e){
                  System.out.println("Exception Name : Some Other exception");
          }
          System.out.println("code flow continues after the try-catch block...");
}
}

Output :

Exception Name : ArithmeticException

code flow continues after the try-catch block…

2. finally 

finally java keyword is an optional block of code used in try-catch block.

finally block in java is used to close the open resources like DBConnections, after the catch exception process completed.

finally block executes always whether exception occurred or not.

Syntax :

try {
    //Statements ...
}
catch (exception-type exception-object){
   //Statements ...
}
finally {
   //Statements ...
}

Examples :

public class tryCatchExample{
        public static void main(String args[]) {
                try{
                        int a = 99;
                        int num=a/0;
                        System.out.println(num);
                }
                catch(ArithmeticException e){
                        System.out.println("Integer a is 99 and should not be divided by zero");
                }
                finally{
                        System.out.println("finally block is executed");
                }
                System.out.println("Code flow continues after try-catch-finally statements");
        }
}

Output :

Integer a is 99 and should not be divided by zero

finally block is executed


Code flow continues after try-catch-finally statements

case 1 :

when there is exception in the code and are not handled properly. 

Example :

public class tryCatchExample{
 public static void main(String args[]){
     try{
        int a = 65;
        int num=a/0;
        System.out.println(num);
     }
     catch(ArrayIndexOutOfBoundsException e){
        System.out.println("ArrayIndexOutOfBoundsException");
     }
     finally{
        System.out.println("finally block is executed...");
     }
     System.out.println("Code flow continues after try-catch-finally block");
   }
}

Output :

finally block is executed…

Exception in thread “main” java.lang.ArithmeticException: / by zero

at tryCatchExample.main(tryCatchExample.java:5)

case 2 :

When exceptions are properly handled in catch block

Example :

public class tryCatchExample{
   public static void main(String args[]){
      try{
         int a = 60;
         int num=a/0;
         System.out.println(num);
      }
      catch(ArithmeticException e){
         System.out.println("Exception Name : ArithmeticException");
      }
      finally{
         System.out.println("finally block is executed...");
      }
      System.out.println("Code flow continues after try-catch-finally block");
   }
}

Output :

Exception Name : ArithmeticException

finally block is executed…

Code flow continues after try-catch-finally block

Throw and Throws in java explained below.

3. throw

Throw keyword is used to throw the known exception to the runtime environment to handle the exception.

throw can throw exceptions for both checked or unchecked exception.

throw will throw custom exceptions.

Syntax :

throw exception;

Example :

public class tryCatchExample
{   
public static void main(String args[])
{      
validate(20);      
System.out.println("code flow continues to the next step...");  
}  
static void validate(int age){     
if(age<21)  throw new ArithmeticException("age is not valid...");     
else      
System.out.println("age is valid...");   
}
}

Output :

Exception in thread “main” java.lang.ArithmeticException: age is not valid…

at tryCatchExample.validate(tryCatchExample.java:8)

at tryCatchExample.main(tryCatchExample.java:3)

4. throws

Throws keyword in java indicates that this particular method might throw exceptions, it may be Catched or Uncatched exceptions.

The programmer have to handle the method code by using try-catch block for the method.

Syntax :


return_type method_name() throws exception_class_name{  
//method code  
}  

Example :

import java.io.*;

class innerClass{
void checkExp()throws IOException{
throw new IOException("Error inside the method...");
}
}
public class tryCatchExample{

public static void main(String args[]){
try{
innerClass c = new innerClass();
c.checkExp();
}catch(Exception e){
System.out.println("exception handled properly...");
}
System.out.println("code flow continues ...");
}
}

Output :

exception handled properly…

code flow continues …

What are custom exception in Java?

We can create your own exceptions in Java, that means we can make an exception by our own.

All exceptions must be a child of Throwable.

If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.

If you want to write a runtime exception, you need to extend the RuntimeException class.

Syntax :

class MyException extends Exception {
}

User defined exception in java.

Example :

class CusException extends Exception {
int id;
public CusException(int a) {
id = a;
}
public String toString() {
return "CustomException[" + id + "]";
}
}
public class tryCatchExample {
public static void main(String args[]) {

try {
checkCondition(15);
checkCondition(26);
} catch(CusException e) {
System.out.println(e);
}
}

static void checkCondition(int num) throws CusException {
if (num > 25)
throw new CusException(num);
System.out.println("There is no exception in the program...");
}
}

Output :

There is no exception in the program…

CustomException[26]

Assertions in Java

What are Assertions?

Assertion is a java statement by which we can test our assumptions(assuming value) in your program.

It is achieved by “assert” keyword in Java. 

By default assertion value is “true” during the runtime.

If the assert case failed JVM throws an AssertionError.

This is mainly useful in testing purpose in the development environment.

Syntax :

assert expression;

assert expression1 : expression2;

Example :

class assertExample
{
    public static void main( String args[] )
    {
        int num = 10;
        assert num >= 15 : "Not Equal";
        System.out.println("number value is "+num);
    }
}

Output :

number value is 10

Enabling and disabling assertions in development environment

Enabling Assertions

By default, assertions are disabled. To enable assertions we need to follow the syntax given below.

The syntax for enabling assertion statement in Java source code is:


java –ea assertExample

or

java –enableassertions assertExample

Here, Test is the file name.

After enabling assertions the output will be

Output :

Exception in thread “main” java.lang.AssertionError: Not Equal

at assertExample.main(assertExample.java:8)

Disabling Assertions

To disable the assertion we need to follow the syntax given below.

java –da assertExample

or

java –disableassertions assertExample