Today's Offer - Java Certification Training - Enroll at Flat 10% Off.

- Java Blogs -

What is Exception in java? Type of Exception Handling in Java

Java was developed by Sun Microsystems in 1995 and is considered as a high-end programming language which can operate on many platforms like the Windows, Mac OS and even different versions of UNIX. Java SE 8, is considered as the latest version of Java Standard Edition. Many configurations were built in Java to cater to different platforms due to its increasing popularity. It was guaranteed to be Write Once, Run Anywhere. It is endowed with many advantages like bring simple, secure, portable, robust, dynamic, multithreaded, etc.

What are Exceptions in Java?

An exception in Java is basically an unexpected or an exceptional event which has occurred during the execution of a program, i.e., during run time and often leads to disruption of the program. It results in abnormal termination of the application, which is of course not recommended, and thus it becomes imperative to take care of the exceptions in time. These can occur due to many reasons. Some of these are:

  • Invalid Data entered by User
  • The file cannot be found
  • Interrupted network connection which has been lost while you were in the middle of all the communications or even the JVM has run out of memory.

It is apparent that some of these errors are caused by the user while others are programming errors and some by the failure of some of the physical resources due to some mechanical issue. Thus, the exceptions can then be classified into three different categories:

  • Checked Exception: A checked exception is the one which is being notified or checked by the compiler at the time of compilation. These are therefore called the checked exceptions, and these cannot be ignored and have to be handled by the programmer.
  • Unchecked Exception: An unchecked exception is the one which occurs at the time of execution and is also known as Runtime Exceptions. Many programming bugs like the logic errors or improper use of API, etc. All the Runtime Errors are often overlooked or ignored at the time of compilation.
  • Errors: These are not placed in the category of exceptions. These are basically the problems which have come up and are not under the control of the programmers. Often the errors are ignored in the code as nothing much can be done about them.

Common Terminology    

  • Call Stack: It refers to a list of methods which is highly ordered and has been specifically called for getting a specific method.
  • Exception Class: It refers to the type of error which has occurred and is part of the inheritance hierarchy, which is used for grouping similar errors.
  • Exception Object: It is basically an instance of the exception class. It generally gets created and handed to the Java runtime whenever an exception has taken place and has resulted in disruption of the application.

Why are Exceptions used?

The reasons why the exceptions are used are as follows:

  • They are helpful in the separation of the error-handling code from the regular code which gives more clean algorithms which are completely free of the trash.
  • They help to propagate errors in the call stack. Thus the nested methods do not have to catch and forward the errors explicitly hence making the work more reliable.
  • Also, the exception classes help in grouping and differentiating various error types. Errors can be grouped by generalizing the parent class and by differentiating them by their actual class.
  • Finally, error handling is standardized.

Hierarchy of Exceptions

All the exceptions in Java, along with the Errors, are part of the Throwable class. Throwable is considered as the elementary class of the hierarchy. Under Throwable, there are two branches one led by Exceptions and the other led by Errors. The exception is used for some of the exceptional conditions which should be caught by the user programs; for instance, the NullPointerException is one such example. The Error is used by the JVM or the Java run-time system for indicating errors which have to do with the run-time environment of Java or the JRE, for instance, StackOverflow Error is an example of the error.

Read: What Is Static Class In Java? List of Static Nested Classes In Java

Hierarchy of Exceptions

Handling of Exceptions

Handling of Exceptions by JVM

Default Handling:  If an exception has happened inside a method, the method itself leads to the creation of an Object known as the Exception Object and gives it next to the run-time system. The object has both the name and the description of the exception and also the current state of the program where the exception has taken place. This is what is precisely referred to as the throwing of the exception when the exception object is created and handed over to the run-time system. There can be many lists of the methods where the exception has taken place. This list is called the Call Stack. The process of the same is as follows:

  • The call stack is searched by the run-time system for finding the method which has the block of the code which will handled the exception which has taken place. This block of code is basically known as the Exception handler.
  • The run-time system then starts to search the method in which the exception took place, thereby walking through the call stack in the reverse order in which the methods were called.
  • If the right handler is found then the occurred exception is sent to it. Now the right handler means that exception object thrown which completely matches the type of exception object which it can actually handle.
  • If the run-time system has searched all the methods on the call stack and has not found the right handler then the run-time system hands over the Exception Object to the default Exception handler which is again a part of the run-time system. It is this handler which will print the exception information in a particular format and abnormally terminate the program.

Handling of Exceptions by Programmer

Customized Handling: Herein, the Java Exception handling is done by five keywords: try, catch, throw, throws, and finally. All the program statements which can be thought about can actually give rise to exceptions which are contained in the try block. If the exception takes place in the try block, it is basically thrown. The exception can be caught by your code and even handle it rationally by making use of the catch block. Many system-generated exceptions are often thrown by the Java run-time system. In case you want to throw the exception manually, you have to use the keyword throw. Any exception which is thrown out of a method has to be marked by a throws clause. Also, any code which is must be executed after the completion of the try block has to put in the finally block.

Things to Keep in Mind

  • There can be more than one statements in a method which throw an exception. So, all these statements have to be put in its own try block and separate exception handlers have to be provided within own catch block of each of them
  • If an exception has occurred within the try block, that has to be handled by the exception which is linked to it. In order to associate a handler, you have to put the catch block after it. There can be more than one handlers. Every catch block is an exception handler which handles the exception of the type which is mentioned in the argument. The latter, ExceptionType then goes to declare the exception type which it can handle and it has to be the name of the class which inherits from the Throwable class.
  • For every try block, there can be either zero or more catch blocks and only one finally block. Latter is optional. Execution always happens whether an exception has taken place in the try block or not. If in case the exception occurs, then it has to execute after the try and the catch block. And if the exception does not occur, the execution takes place after the try block. The finally block in Java is used for putting significant codes like the clean up code, for instance, closing the file or even closing the connection.

Exception Methods

Here is a list of various methods which are available in the Throwable Class:

  • public String getMessage(): This returns a laid out message about the exception which has taken place. This message is generated in the Throwable constructor.
  • public Throwable getClause(): This returns the cause of the exception as shown by the Throwable object.
  • public String toString(): This returns the name of the class, which is concatenated with the result of getMessage().
  • public void printStackTrace(): This actually prints the result of toString() to System.err along with the stack trace. System.err is the error output system.
  • public StackTraceElement [] getStackTrace(): This returns an array which has every element on the stack trace. The element which is at index 0 it stands for the top of the call stack, and the ultimate element in the array which represents the method which is at the bottom of the call stack.
  • public Throwable fillInStackTrace(): This is used in filling the stack trace of this Throwable object with the current stack trace, thereby adding to any of the previous information in the stack trace.

Catching of Exceptions

An exception is caught by a method by using a  mixture of the try and catch keywords. A typical try/catch block is kept around the code which has to give rise to an exception. Code which is in the try/catch block is known as the protected code and has a particular syntax.


try {
//Protected code
} catch (ExceptionName e1) {
//Catch block
}

The code which is vulnerable to exceptions is kept in the try block. When the exception takes place, it is handled by the associated catch block. Every try block has to be immediately followed by either a catch block or a finally block. A catch statement comprises declaration of the type of exception which you are trying to catch. If on the other hand, an exception occurs in the protected code, the catch block (or blocks) which come after try is checked. If the type of exception which has taken place is mentioned in the catch block, the exception is then given to the catch block just like the argument is passed to the method parameter.

Read: Reactjs Interview Questions and Answers for Experienced

Multiple Catch Blocks

As mentioned above, a try block can have many catch blocks following it, and the syntax for the multiple catch blocks is as follows:


try {
//Protected code
} catch (Exceptiontype1 e1) {
//Catch block
} catch (Exceptiontype2 e2) {
//Catch block
} catch (Exceptiontype3 e3) {
//Catch block
}

There can be any number of catch blocks after the try block. In case the exception has taken place in the protected code, it is thrown into the first catch block which appears on the list. If the data type of the so-called Exception which is thrown is the same as the ExceptionType1, then it is caught there itself. If it is not the case, then the exception has to pass down to the next catch statement. This process is continued until the exception is caught or falls through all the catches. In the latter case, the present method ends the execution and the exception is pushed down to the last method in the call stack.

Throws/Throw Keywords

In case of a method, where the checked exception is not handled, the method has to declare the same by making use of a throws keyword. The latter usually comes at the end of the signature of the method. The exception can be thrown, either a recently instantiated one or the one which has just been caught by making use of the throw keyword.  The difference between the throws and the throw keywords can be stated as follows:

The throws are employed for postponing the handling of a checked exception and throw is used for invoking an exception explicitly.

Finally Block

This block comes after a try block or even a catch block, and it always performs execution even if an exception has occurred. The finally block lets you perform many cleanup-type statements which you have to execute irrespective of the fate of the protected code. The syntax of the final block is as follows:


try {
//Protected code
} catch (Exceptiontype1 e1) {
//Catch block
} catch (Exceptiontype2 e2) {
//Catch block
} catch (Exceptiontype3 e3) {
//Catch block
} finally {
//The finally block always executes.
}

User-Defined Exceptions

Users can also create their own exceptions in Java. There are some points to be considered when doing so. These are as follows:

Read: Hibernate Interview Questions And Answers
  • the exceptions have to come under the Throwable.
  • In case if the user wants to write a checked exception, which can be enforced automatically either by the Handle or Declare Rule, you can have the Exception class extended.
  • Also, if the user wants to write a runtime exception, the RuntimeException class will be extended.

The Exception class can be defined as follows:


Class MyException extends Exception {
}

The predefined Exception class has to be extended for creation of own exception by the users. All these are seen as the checked exceptions.

Common Exceptions

Two categories of Exceptions and Errors are defined in Java:

  • JVM Exceptions: These are those exceptions or errors which are thrown by the JVM. E.g. NullPointerException, ClassCastException, etc.
  • Programmatic Exceptions: These exceptions are often thrown by the application or even the API programmers. E.g. IllegalArgumentException, IllegalStateException, etc.

 Conclusion

The software world is highly prone to errors caused by many factors like a void user input,  a lack of response by an external system or even can be a simple programming error. Whatever the reason, any error which occurs during run-time has to be handled by the application else the whole thing simply crashes and cannot process any more requests. Java has a robust platform which allows handling of all such exceptional events where they basically take place in some of the higher methods of the call stack. You can keep yourself abreast with more of such insightful topics by referring to our website www.janbasktraining.com.


    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Trending Courses

AWS

  • AWS & Fundamentals of Linux
  • Amazon Simple Storage Service
  • Elastic Compute Cloud
  • Databases Overview & Amazon Route 53

Upcoming Class

1 day 14 Nov 2019

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing

Upcoming Class

2 days 15 Nov 2019

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning

Upcoming Class

2 days 15 Nov 2019

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation

Upcoming Class

3 days 16 Nov 2019

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL

Upcoming Class

1 day 14 Nov 2019

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing

Upcoming Class

-1 day 12 Nov 2019

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum

Upcoming Class

2 days 15 Nov 2019

SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design

Upcoming Class

6 days 19 Nov 2019

Comments

Search Posts

Reset

Receive Latest Materials and Offers on Java Course

Interviews