Exception Handling in JAVA

October 12, 2016

What is an Exception?

An exception is some unwanted event which occurs during the execution of a program or code; that disturbs the normal flow of Execution.

For Example: 

You are trying to access a file which doest not exists. It will throw an exception “FileNotFound”.

You are trying to access an element of an array which is more than the size of that array. In that case, you will get “ArrayOutOfBound” Exception.

It is always important to handle all these exceptions, to save your code from irrational behaviour.

The Mechanism of handling runtime error or exception is known as Exception Handling.

Some of the exceptions occur due to user errors and some due to programming errors. Based on this we can classify exception into three categories:

  • Errors
  • Checked Exception
  • Unchecked Exception

Errors:

Errors are something which can not be controlled by the user or programmer. They occur at run-time due to some uncertain conditions like your heap memory get full or if a stack overflow occurs.

Checked Exceptions:

These type of exceptions can be caught at compile time. Say for example you are trying to read a file using FileReader class, at compile time your compiler will prompt to handle an exception called “FileNotFound”.

Unchecked Exceptions:

Unchecked exceptions are also known as runtime exception and cannot be caught at compile time. They occur during execution of code. Logic errors are also considered as a runtime exception.

For Example: Let us consider a scenario where you have defined an integer array of some size say 10, and in code, you are trying to access its 11th value. In this case, your code will throw “ArrayIndexOutOfBound” Exception which is an example of Unchecked Exception.

Hierarchy of Java Exception classes:

The hierarchy of Java Exception starts from Throwable which inherits Object Class of Java. Under Throwable there is an Error class and second is Exception class. Both these classes inherit Throwable Class.

Exception class is then inherited by “Runtime Exception” and then Runtime Exception is inherited by some other Exceptions:

AnnotationTypeMismatchException, ArithmeticException, ArrayStoreException, BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DataBindingException, DOMException, EmptyStackException, EnumConstantNotPresentException, EventException, FileSystemAlreadyExistsException, FileSystemNotFoundException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException, IllegalStateException, IllformedLocaleException, ImagingOpException, IncompleteAnnotationException, IndexOutOfBoundsException, JMRuntimeException, LSException, MalformedParameterizedTypeException, MirroredTypesException, MissingResourceException, NegativeArraySizeException, NoSuchElementException, NoSuchMechanismException, NullPointerException, ProfileDataException, ProviderException, ProviderNotFoundException, RasterFormatException, RejectedExecutionException, SecurityException, SystemException, TypeConstraintException, TypeNotPresentException, UndeclaredThrowableException, UnknownEntityException, UnmodifiableSetException, UnsupportedOperationException, WebServiceException, WrongMethodTypeException

Frequently used Exception Classes:

ArithmeticException – This Exception is thrown when an exceptional arithmetic condition has occurred. For example, an integer “divide by zero”.

IndexOutOfBoundsException – This exception is thrown to indicate that an index of some sort (such as to an array, to a string) is out of range.

  • ArrayIndexOutOfBoundsException – This exception is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
  • StringIndexOutOfBoundsException – This exception is thrown by String methods to indicate that an index is either negative or greater than the size of the string.

FileSystemAlreadyExistsException – This exception is thrown when an attempt is made to create a file system that already exists.

exception handling in java

exception handling in java

Exception handling:

Try-Catch block:

The code which is expected to throw some exception is written in a try block. Catch block catches a particular exception and does some task. There can be multiple exception blocks, these blocks handle exceptions in a hierarchy  but in reverse order.

Try-Catch-Finally block:

Try-catch block is already explained above. “Finally” block is one which will be executed as the last block in code. This will be executed in both scenarios whether an exception occurs or not.

Throws keyword:

A method can be called by another method. When we want to handle an Exception in calling method instead of called method, in that case, we can use throws keyword in called method and try-catch block in calling method.

Throw keyword:

“Throw” keyword is used to explicitly throw a customised exception. For Example:

PS: For any questions, queries or comments feel free to write us at support@qatechub.com or saurabh@qatechhub.com

Saurabh

About the Author

Saurabh

Follow Saurabh:

Leave a Comment: