Skip to main content

Introduction to Java Programming

  What is Java? Java is a programming language and a platform. Java is a high-level, robust, object-oriented and secure programming language. Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is known as the father of Java. Firstly, it was called  Greentalk  and the file extension was  .gt . After that, it was called  Oak . Initially Java was designed for small, embedded systems in electronic appliances like set-top boxes. Platform:  Any hardware or software environment in which a program runs, is known as a platform. Since Java has a runtime environment (JRE) and API(Application Programming Interface), it is called a platform. The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High performance, Multithreaded, Architecture neutral, Object-oriented, Interpreted, and Dynamic". Currently, Java is used in internet programming, mobile devices, games, e-business so

27. Exceptions Handling in Java

 

Exception Handling in Java

  • Exception handling is a mechanism to handle run-time errors such as ClassNotFoundException, IOException, SQLException etc.
  • To maintain the normal flow of the program, we requires exception handling in our program.
  • Exception handling is mainly for the checked exception, because unchecked exceptions occurs because of the silly mistakes of user.
  • The printStackTrace() method of java.lang.Throwable class is used to print this Throwable along with other details like class name and line number where exception occurred.

How JVM handle an Exception?

  • The method creates an object known as Exception Object and hands it off to the run-time system (JVM). This is known as throwing an exception.
  • The Exception Object contains name and description of the exception, and current state of the program where exception has occurred.
  • Now, there might be the list of the methods that can be called to get the method where exception was occurred. This ordered list of methods is called CallStack.
  • The JVM searches the CallStack to find the method that can handle the occurred exception. This method is called Exception Handler.
  • If the JVM searches all the methods on CallStack and couldn't have found the appropriate handler, then JVM handover the Exception Object to default exception handler.
  • This handler prints the exception information and terminates the program abnormally.

How Programmer handles an Exception?

Java Exception handling is managed via five keywords:

  • try
  • catch
  • finally
  • throw
  • throws

try block

  • The try block is used to enclose the code that might throw an exception.
  • If an statement in try block raised an exception, then the rest of the try block doesn't execute.
  • The try block should not contain the important statements that need to be printed regardless of the exception occurs or not.
  • Java try block must be followed by either catch or finally block.

catch block

  • Java catch block is used to handle the Exception by declaring the type of exception within the parameter.
  • After executing try block, the control passes to the corresponding catch block.
  • After executing the catch block, the rest of the program will be executed.
  • The declared exception may be the parent class exception (i.e. Exception class) or the generated exception type.
  • We can use multiple catch blocks with a single try block.
  • If the exception is not handled by the programmer, then JVM handles it.

finally block

  • The finally block executes whether an exception rise or not and whether exception handled or not.
  • The finally block in Java is used to put important codes such as clean up code e.g., closing the file or closing the connection.
  • It should contain all the necessary statements that need to be printed regardless of the exception occurs or not.

throw

  • The throw keyword is used to throw an exception explicitly.
  • We specify the exception object which is to be thrown.
  • The exception has some message with it that provides the error description.
  • The flow of execution of the program stops immediately after the throw statement is executed, and the nearest enclosing try-catch block is checked that matches the type of exception.
  • We can throw either checked or unchecked exceptions in Java by throw keyword.
  • We can also define our set of conditions and throw an exception using throw keyword.

throws

  • The throws keyword is used to declare an exception in the signature of method.
  • It gives an information to the programmer that there may occur an exception.
  • So, now it's the programmer responsibility to handle that declared exception.
  • The caller of these methods has to handle the exception.
import java.util.Scanner;

class Calculator {
    public static double add(double a, double b) {
        try {
            double sum = a + b;
            return sum;
        } finally {
            System.out.println("\nThis is inside finally block 1...");
        }
    }

    public static double sub(double a, double b) {
        try {
            double diff = a - b;
            return diff;
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("This is outside finally block...");
        return -1;
    }

    public static double mul(double a, double b) {
        try {
            double pro = a * b;
            return pro;
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("This is outside finally block...");
        return -1;
    }

    public static double div(double a, double b) {
        try {
            return a / b;
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            System.out.println("\nThis is inside finally block 2...");
        }
        return -1;
    }

    public static int div(int a, int b) {
        try {
            return a / b;
        } catch (Exception e) {
            System.out.println("\nThe exception is: " + e);
        }
        System.out.println("This is outside finally block...");
        return -1;
    }
}

class TryCatchFinally {
    public static void main(String[] arr) {
        double a, b;
        int c, d;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter two numbers: ");
        a = input.nextDouble();
        b = input.nextDouble();
        System.out.println("The sum of " + a + " and " + b + " is " + Calculator.add(a, b));
        System.out.println("\nThe difference of " + a + " and " + b + " is " + Calculator.sub(a, b));
        System.out.println("\nThe multiplication of " + a + " and " + b + " is " + Calculator.mul(a, b));
        System.out.println("The division of " + a + " and " + b + " is " + Calculator.div(a, b));
        System.out.print("\nEnter two integer values: ");
        c = input.nextInt();
        d = input.nextInt();
        System.out.println("The division of " + c + " and " + d + " is " + Calculator.div(c, d));
        input.close();
    }
}

Output :

Enter two numbers: 20 0

This is inside finally block 1...
The sum of 20.0 and 0.0 is 20.0

The difference of 20.0 and 0.0 is 20.0

The multiplication of 20.0 and 0.0 is 0.0

This is inside finally block 2...
The division of 20.0 and 0.0 is Infinity

Enter two integer values: 20 0

The exception is: java.lang.ArithmeticException: / by zero
This is outside finally block...
The division of 20 and 0 is -1

Note: 0.0 is a double literal and this is not considered as absolute zero! No exception because it is considered that the double variables are large enough to hold the values representing near infinity!

import java.util.Scanner;

class ThrowThrows {
    public static void main(String[] arr) throws ArithmeticException {
        int a = 500, b, c;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number to divide 500: ");
        b = input.nextInt();
        input.close();
        c = b;
        try {
            if (c == 0)
                throw new ArithmeticException();
            else
                System.out.println("The result is " + a / c);
        } catch (Exception e) {
            System.out.println("The exception is " + e);
        }
        System.out.println("If we use throw inside Try-catch block, then code after Try-catch block executes...\n");
        if (b == 0)
            throw new ArithmeticException("Exception occured...");
        else
            System.out.println("The result is " + a / b);
        System.out.println("This throw is outside Try-catch block, so it will not executed...");
    }
}

Output :

Enter a number to divide 500: 0
The exception is java.lang.ArithmeticException
If we use throw inside Try-catch block, then code after Try-catch block executes...

Exception in thread "main" java.lang.ArithmeticException: Exception occured...
              at ThrowThrows.main(ThrowThrows.java:102)

Previous

Next

Comments