Exception in Java

Exceptions are events occurring during a program execution which interrupt the regular flow of data. In java, exceptions are objects which wrap error events that happen inside a method and contain details about the error and its type.



  • There are some exceptional cases in java which throw an exception

  • In mathematics, 1/0 is infinity, but in java this is an exceptional case. This terminates a program.
    In this chapter, we will learn about of ‘try’, ‘catch’, ‘finally’, ‘throws’ and ‘throw’ and the use of these five keywords in industry or business.

  • All exceptions occur only at runtime while syntax errors occur at compile time.


Why do we need to Learn Exception?
Consider the program below. It executes properly and prints the output


Now add one exceptional code in between, which is shown in bold.

Exception in thread "main" java.lang.ArithmeticException: / by zero at com.javabykiran.Exception.Exception.main(Exception.java:10).

  • In this case we are not able to get an output as expected as the exceptional case is in the middle. After learning this chapter we will be able to run anything and everything by handling such exceptional conditions.

  • Here you can see that the client will see this error message and it is not user friendly. It is better to show a more user friendly message.

  • We summarise the two uses
    • to make a continuation of a program
    • to avoid java error messages and to provide good, user friendly messages

Shown below is the hierarchythrowable exception hierarchy in java
throwable error hierarchy in java

  • In the above given Hierarchy Throwable is a class which is at the top of the exception hierarchy, from which all exception classes are derived.

  • It is the super class of all Exceptions.

  • Only objects which are instances of this class can throw exception by using the throw statement.

  • Only object of this class or one of its subclasses can be the argument type in a catch block.

  • Problems faced during the program execution be divided into two types:
    • Exceptions
    • Errors

  • Both Exception and Errors are java classes which are derived from the Throwable class

  • Error is subclass of throwable class and it terminates the program if there is a problem related to system or resources. It signifies a serious problem in the application and are mostly abnormal conditions.

  • Error does not occur because of the programmer’s mistakes, but when system is not working properly or a resource is not allocated properly.

  • Memory out of bound exception, stack overflow etc., are examples of Error.

  • Only object of this class or one of its subclasses can be the argument type in a catch block.

  • It is common to make errors while developing or typing a program and this may cause the program to produce unexpected results. It is therefore necessary to detect and manage the error conditions in the program so that the program doesn’t terminate during the execution.

  • Sun Microsystems has categorized all exceptions in different categories. For example, for all arithmetic operations are under class called ArithmaticException.java

  • For all sql type of exceptions, they created a class called SQLExcption.java, and so on.

  1. Take a look at the above class ExceptionDivideByZero.java [in the beginning of this chapter]

  2. When the interpreter reads the line int a=1/0;

  3. The control goes to JVM and it searches for a category of exception. In this case it is Arithmetic exception.

  4. The JVM creates an Object of that class, then it comes back to the same line again with a reference variable of ArithmaticException class.

  5. It does check if this line is in the try block.

  6. If No, then it goes to the console and prints a message by the getMessage method of ArithmaticException class.

  7. The program terminates and won’t come back to our program again.

  8. If Yes, refers to the program given below with try and catch

  9. In this case, it looks for the corresponding catch block and then it sees which class is there in this case (Exception).

  10. In this case, the compiler assigns Arithmetic class’s object to Exception reference variable.

  11. Exception e = new ArithmeticException();

  12. If the above (11) is correct, then it enters in the catch block.

  13. If it is not correct, then it considers that the try catch is not written and goes back to console and prints error. Point : 5

  14. After executing catch block, the cursor goes to the next line and the execution continues 333 then 444.

  15. This is because as soon the interpreter see the exception, it goes for catch block, not in between sentences. In our case it is ‘after divide’
    Some rules are below:

    • Try should be followed by only catch or only finally block or multiple catch or multiple catch and single finally

    • When exception is not raised in the try block statements then catch block will not be executed

    • You can write multiple try-catch blocks

    • When you are writing a multiple catch block, then order or exception must first be subclass and then superclass

    • When exception is raised in the try block statements then only one matching catch block will be executed

    • You should not write any statement between try block and catch block

    • We can write this combination anywhere inside the method. Given below are various combinations that are allowed

If we have a requirement of inserting 100 students to DB subject to the condition that if there is any issue in insertion for any student, it should not impact the other students. Now,the requirement is to Add 100 student but if any student fails, other students should not get inserted

The finally block is used when an important part of the code needs to be executed. It is always executed whether or not the exceptions are handled.

  • Finally block will always get executed until we shut down JVM. To shut down JVM in java we call System.exit (); or we have infinite loop in try block.

  • Occurs irrespective of any exception.

  • Occurs irrespective of any return value in try or catch.

  • Normally, finally block contains the code to release resources like DB connections, IO streams etc.

  • You can also write resource cleanup code inside the finalize() method. But finally block is recommended rather than the finalize method for resource cleanup.


Question. What is the difference Between Catch and Finally in java?

Sr. No. Catch Finally
1 Catch block handles the error when it occurs in try block There is no need of exception thrown by try block
2 Catch block is executed only when the if exception is thrown by try block, otherwise it is not executed Finally block is always executed whether exception occurs or not
3 We can use multiple catch block for only one try block Only one finally block is used for one try block
4 We can handle multiple exceptions by using catch blocks It is not for exception handling

Examples: check compile time error and runtime output in some cases
Question: Will it compile?

Answer: It will not compile (Unreachable code)
return 40;


Question: What will this method return?

Answer: 30

Why are they needed?
To delegate exception from one class to another we use throw and throws.
Consider the case below:

  • Consider the above code where A is sending a request to B and

  • then to C and then to D

  • If the exception occurs at class C m3 method, then what message will A get? Nothing,Program will get terminated at C class

  • If we use try and catch at every class and every method then exceptions will get handled but message will not be transferred in the reverse direction, which is from C to B and then to A

  • So, to delegate these types of exceptions to caller of the method we use throw and throws from one class to another

  • Here, C will delegate its exception to B’s m2 and then B’s m2 will delegate to A’s m1 (); there we will write try and catch and will give an user friendly message

  • This scenario is more appropriate when there is remote calling. For example, FLIPKART calls to ICICI bank then ICICI to AIRTEL for sms and to mastercard for authorisation

  • In this case, the whole infrastructure is different. This means that there is different ram and different hard disk for every entity. So, if we click a button in FLIPKART and something happens at the ICICI’s end, we will just keep waiting. But by using throw, throws we will get a message that is delegated by ICICI

RuntimeException is a superclass of exceptions that may be thrown in the regular course of operation of JVM. Runtime exceptions and its subclasses are known as unchecked exceptions.

  • This exception occurs at runtime. Actually, even checked exception occurs at runtime

  • All exceptions under runtime exception class are called runtime exceptions or unchecked exceptions

  • In the industry, it is not expected that the developer leave these exceptions in the program 1/0 operation … developer should check before this that whether no is zero

    if( b > 0 ){
        int c=a/b 
     }
    
  • If any method throws runtime exception, then the caller is not restricted to handle that exception.

See the example below:

All exceptions which are not runtime exceptions are compile time exceptions.
They are checked at compile time.

  • These exceptions are those which are not under runtime exception class hierarchy

  • If thrown from any method, they must be handled by caller of the method otherwise it gives compile time error

  • The most confusing thing is that some people say it occurs at compile time. That is wrong; exception always occurs at runtime only

  • If any method throws runtime exception, then the caller is not restricted to handle that exception.

See the example below:

OR


Throw:

The throw keyword declares an exception. It tells the user about the error and helps the user create an exception handling code from the outset.

  • Throw keyword is used to throw the exceptions

  • Normally JVM is responsible for identifying the exceptional java class, creating its objects and throwing that object

  • You can use the throw keyword with this syntax: throw object;
    Example:

    throw new ArithmeticException(); 
               or
    ArithmeticException ae = new ArithmeticException(); 
    throw ae;
    throw new StudentNotFoundException():    
    

Throws:

  • Throws keyword is used to specify the method level exceptions

  • If any method throws compile time exception then caller should :

    1. Handle that exception by writing try a block inside the method

    2. Or propagate the exception to caller of the method level exception using throws keyword


Question : What is the difference between Checked Exception and Unchecked Exception keyword?

Sr. No. Checked Exception Unchecked Exception
1 Checked Exceptions are checked at compile time. Unchecked exceptions are not checked at compile time.
2 Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling. Unchecked Exception doesn’t have to be caught or declared thrown.
3 Checked exceptions in Java extend the java.lang.Exception class. Unchecked exceptions extend the java.lang.RuntimeException.
4 Checked Exception represents a scenario with higher failure rate. Unchecked Exception occurs mostly due to programming mistakes.
5 Checked Exception needs to be handled by the caller. Unchecked exceptions are not handled by the caller.
  • Exception represents the problem which can be solved whereas error represents the problem which cannot be solved.

    Exceptions can be handled and can contain the program execution where as errors cannot be handled

    Some examples of exceptions are:
    ArithmeticException, IOException, etc.

    Some examples of errors are:
    NoSuchMethodError, ClassDefNotFoundError, OutOfMemoryError StackOverflowError, etc.

  • All exceptions and errors will always be thrown at runtime only.

  • Error comes at runtime and syntactical error comes at compile time.

Sr. No. Exception Error
1 Exceptions are related to the application. Error is related to the environment in which the application is running.
2 Exceptions may not be fatal in all cases. An Error can't be recovered as it is fatal in nature.
3 An Exception is basically divided into two categories, i.e. Checked and Unchecked Exceptions. A Checked Exception has a special place in the Java programming language and requires a mandatory try catch finally code block to handle it Unchecked Exception is a subclass of Runtime Exception that usually represents programming errors. An error is basically divided into 2 categories
  1. Compile Time
  2. Runtime
4 Exceptions can be checked or unchecked. Programmer should handled at the application level. Errors are always unchecked and usually indicate a system error or a problem with a low level resource and should be handled at the system level, if possible.
5 Handling an Error is not a good idea because recovery from an Error is usually not possible.