Exception Handling in Java: Hierarchy Example and Types

One of the important topic Exception handling in java

Here we will discuss basics of exceptions, Why Exception handling and its types.

What is Exception in Java

A unwanted event that disrupts the program execution.

In Java all Exceptions are class.

Why Exception Occurs

  1. Due to wrong user input
  2. Incorrect programming logic

Example of Exceptions

  1. Dividing a number by zero 5/0 . It will throw ArithmeticException
  2. Converting a String to number Integer.parseInt("123s"). Exception It will throw NumberFormatException 
  3. Accessing beyond index in Array a[100] when only 5 elements are in array. Throw ArrayIndexOutOfBoundsException

ArithmeticException on Java Program

What is Exception Handling in Java

Exception can terminate the program execution.

To handle unwanted event and to execute rest of the program exception handling is required

On exception Java shows programmer friendly message. To show end used we need to provide custom message

How to Handle Exception in Java

Java provides keywords to handle the exception

Java exception can be handle by 5 keyword  try, catch, throw, throws and finally.

  1. try : Any Program statement that we want to check for exception must be placed  within a try block.
  2. catch  :  If the exception occurs within try block it is thrown. Your code can catch this exception (using catch) and handle it.
  3. throw  :  if an exception arises then this system-generated exception is automatically thrown by Java run time system. To manually throw an exception, throw keyword used.
  4. throws  :  A throws clause lists the type of exception that a method might throw.
  5. finally  :  In programming, we want any code must be executed after the try block completes is placed within a finally block.


try block can be used either with a catch or finally block or with both but try cannot be used alone.

A try can have multiple catch block.

When there is an exception in the try block an appropriate catch block is executed based on the exception.

Exception Hierarchy in java

In java programming, Exception class is a subclass of class Throwable.

Apart from the Exception class, class Error is also derived from class Throwable.

Fig: Exception Hierarchy

Error: In java programming, error is Unrecoverable. It occurs during compile time.

For example, if we write wrong syntax then error will generate during compile time.

Root class of exception in java

Throwable is the root class of exception in Java

Types of Exception in Java

  1. Checked Exception
  2. Unchecked Exception

Checked Exception in java

Exceptions that are checked by compiler is called checked exceptions.

On compiling above program.

Checked Exception in Java
Fig: Checked Exception

To make code executable we must surround Scanner with try and catch the FileNotFoundException.

Here is the list of some checked exception

  1. IllegalAccessException: in java programming, this exception occurs when access to a class is denied.
  2. ClassNotFoundException: this exception occurs when class not found.
  3. NoSuchMethodException : when a requested method dose not exist this exception occurs.
  4. CloneNotSupportedException: in java programming,If you are trying to use the clone method in a classwhere Cloneable interface is not implemented, it throwsCloneNotSupportedException. Clone() method is used to create exactcopy of a object
  5. InterruptedException : in java, when we work with multiple threads then one thread  interrupts another thread.  

Unchecked Exception in Java

Exception condition is not checked by compiler.

Runtime class and its sub classes are known as unchecked exception.

Compiler does not flag any error if there is unchecked exception.

Fig: Unchecked Exception compilation
  1. ArithmeticException : in java programming, this exception, represent the arithmetic error, such as divided-by-zero.
  2. IndexOutOfBoundsException: when some type of index is out of bounds this exception occurs.
    • ArrayIndexOutOfBoundsException: in java programming, this exception represents the Array index is out of bound. This condition arises when we try to access the illegal array index.
    • StringIndexOutOfBoundsException: in java programming, when we access the index outside the bounds of string then this exception occurs.
  3. NegativeArraySizeException: when an array is created with a negative size then this exception arises.
  4. NullPointerException: in java programming, this exception occurs when invalid use of null reference.
  5. IllegalThreadStateException: this exception occurs when the required operation not compatible with the current thread state.

What is difference between checked and unchecked exception in java

Checked Exceptions are checked by compile at compile time.

Unchecked Exceptions are not checked by compiler.

Advantages of Exception Handling in Java

  1. Error handling is separate from Regular code
  2. Propagating Errors Up the Call Stack
  3. Grouping and Differentiating Error Types

Read More

  1. Exception Handling in Java with Examples
  2. Exception Handling try catch finally blocks in Java
  3. Throw and Throws Keywords in Java


Advantages of Exceptions

PHP Abstract Class

Abstract keyword is another new functionality in OOPS.

When a class declare by Abstract keyword this class cannot be instantiate. Means if user declares a class as an Abstract class he or she cannot create object of that class.

Abstract class is only use for inheriting another class. Main purpose of creating abstract class is to protected or restricted from direct object creation.



PHP Final Class

In PHP 5 a new mechanism added in OOPS which is Final Keyword.

If a class declares by final keyword then the class never extended. Child class can’t be created of any Final class.

It is restrict the overriding a method.

Only class and function may be declared as Final but no variable or properties cannot declare as Final.



PHP Inheritance

Inheritance is a wonderful feature of OOPS. It is solved the duplication of code.

Code duplication happened when user uses same code multiple times. Using Inheritance declare the logic in one class and extends it whenever needs to use it. And also add new functionality with old one.

In Inheritance, there have parent or base class and a child or derived class. Write logic in parent class onetime and reuse it many times in child class.

Child class has the power to access all or a few methods and variables of the parent class. Child class has also own member variables or functions.

Child class has the power to access all or few methods and variables of the parent class. Child class has also own member variables or functions.

How to extend Parent or Base Class


Parent Class:  A class which is inherited from another class that is called parent or base or superclass.

Child Class: A class which is inherits from another class that is called child or sub or derived class.

In this above example, Animal is a parent or base class and Dog is a Child class.

Dog class can access Animal class member variable and function for Inheritance. Extends keyword helps to create a child class.

Whenever wants to inherit parent class then need to use extends keyword to create child class.

Child class cannot access all properties of parent class. In PHP there are 3 types of Access Specifiers.

Public: By default all class member variable and functions are public member.

All public members of parent class can, by child class and also out of the uses. Public member define by Public Keyword.

Private: Private member defines by Private Keyword. Only Parent class can be accessed Private property.

Private property cannot be access in child class and out of the class.

Protected: Protected Member defines by Protected Keyword. Protected Members are only access into Parent Class and its child class.

Protected property cannot access out of the class.


Five Types of Inheritance in Programming Language:

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multilevel Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

But in PHP only Single and Multi-level inheritance supported.

  1. Single Inheritance: There only one base class and one child class. Child class only derived from one base class.


  1. Multi-Level Inheritance: There one base class derived one child class and that child class derived another child class and so on.


PHP Constructor and Destructor

If the user wants to access any member function of a class then he or she must create the object first then call the member function by this object.

The constructor is a method or way which automatically called when an object the for a class.

No need to call it by an object. Simply constructor is a function which called when object creates of class.

Constructor declares by two ways.

  1. Define function name same as class name. (This is old way to declare constructor. It is use in PHP 5.3.3 version)
  2. Define function by __construct keyword.

Only one constructor creates in one class. It is used to run an operation which needs to run at first of any other operation.

Like Database Connection. The constructor




In above example $dell is an object of Computer class when its created constructor automatically called and CPU, RAM and Hard disk value passed by parameter.

Then when called describe() function its return the whole value


the is also a method or way in OOPS which is opposite of Constructor.

Destructor also called automatically when object an of any class but it’s run when The constructor creates.

It the for free up memory. Using this after complete a task unset all variable and re The constructor it in next program.

Destructor defines by __destruct keyword. an is also a function which automatically called when object The constructor.



PHP Class and Objects

Class and objects is a programming template to write a program in a block.

It is helps to developer write complex program in simple way, reuse a program in multiple applications and create a structural program.

A class has two member one Variables and two Functions. A class is a program structure where developer defines application logic.

Object is a way which use to access class. Create an object developer access their application logic which defines in a class anywhere in a project.

Class and Object is a very useful and easy way to create a complicated application in a simple way.

Creating Class:    


Create a class with “class” keyword then define a class name. The name must start with string or underscore (_).

PHP is a case sensitive language so class name also case sensitive. Means Pen is write word to access this class. start PEN,  pEn, The name not the same.

Between { } define whole logic or code. Variable must be declared with var keyword or public keyword and all logic operation must be defined in function.

Creating Object


new keyword create object of a class. Object has authority to access the class variable and function out of the class.

In this example $obj is an object of Pen class, $obj can access $name, $price or can call the describe() function out of the class.

Object never creates within class.

Accessing Members and Functions



Accessing class member variable and function by object. “->” this is accessing symbol.

$this variable is use to access class member variable in to the class member function. $this is object pointer, with reference an instance of class.

Bootstrap Text

Bootstrap has a lot of utilities for controlling the styling and display of text content on web applications.

You can control the tex alignment, size, color and much more. Here we will be discussing all such features.

Bootstrap Text alignment

Firstly, let’s start with the text alignment. The horizontal alignment of the text can be controlled using four Bootstrap contextual classes namely:

  • .text-left: For left aligning the text
  • .text-right: For right aligning the text
  • .text-center: For center aligning the text
  • .text-justify: For a justified alignment (all lines with same width)

Check the code below for illustration:

To control the alignment as per the screen size you can use the text-* classes.

Here, the start can be replaced with sm for small, md for medium and lg for large screen size.

The following code snippet shows the use of this classes with left alignment.

Bootstrap Text wrapping and overflow

You can also prevent the text content from wrapping within a limited width. This can be done by using the .text-nonwrap class. For example:

You can also use the .text-truncate class for longer content.

This will truncate the text with an ellipsis.

Please note that display: inline-block or display: block is required for this to work properly.

Here’s the code for inline:

Bootstrap Text transform

You can transform some text for its case. In other words, Bootstrap provides you some utility classes that help you change the case of the , .

These classes are:

  • .text-lowercase: Transforms whole text into lower case
  • .text-uppercase: Transforms whole text into upper case
  • .text-capitalize: Transform only the first letter of each word to uppercase

Bootstrap Font weight and italics

So far we studied how Bootstrap helps us control the alignment, size, flow, and case of the text.

But as far as styling is concerned, there’s one more important thing that we need to know, It is called the text weight.

The text weight basically decides whether the text is bold, normal or light. The code below will show you the uses of the classes, .font-weight-bold, .font-weight-normal, font-weight-light for the same.

Another thing that you can see is italicising the text using the .font-italic class.

Have a look:

Bootstrap Vertical Alignment

The vertical alignment of the web-page components is a helpful styling feature.

You can align the positioning of the elements might not always go as expected especially when you’re using the different type of elements in one line (like text with image).

In such cases, altering the vertical alignment can help with a better neat positioning.

To understand the concept of Vertical alignment better, let’s have a look at the following CSS code:

From the above code, we can understand that  vertical alignment can be controlled using following basic properties:

  • baseline: Vertically aligning the element with the baseline of the parent element
  • text-top: Vertically aligning the element with the top of the parent’s font
  • text-bottom: Vertically aligning the element with the bottom of the parent’s font
  • sub: Vertically aligning the element with the subscript of the parent
  • super: Vertically aligning the element with the superscript of the parent

Now that, you are familiar with the basic ways in which an element can be vertically aligned then lets dive into the concepts of Bootstrap to know about its features and support for this.

Controlling Vertical Alignment in Bootstrap

With the help of Bootstrap, you can control the vertical alignment of the following elements:

  • inline
  • inline-block
  • inline-table
  • table cell elements.

Here’s the list of Bootstrap utilities for vertical alignment. You can easily draw similarities between these and the CSS properties we just saw:

  • .align-baseline: Vertically aligning the element with the baseline of the parent element
  • .align-top: Vertically aligning the element with the top of the element that is the tallest in the line
  • .align-middle: Vertically positioning the element in the middle of its parent element
  • .align-bottom: Vertically alignin the element with the element that is the lowest in the line
  • .align-text-bottom: Vertically aligning the element with the bottom of the parent’s font
  • .align-text-top: Vertically aligning the element with the top of the parent’s font

These utility classes will be used to control the vertical alignment of the element on the web page.

Let us now check out how different type of elements, are vertically aligned in Bootstrap:

Bootstrap Inline elements

The below code will illustrate vertical alignment for inline elements for baseline, top, middle, bottom, text-top and text-bottom

Table Cells

Bootstrap Float

The Float utility ensures the responsiveness of the content for the web-applications.

You can toggle floats on your web-page element making them more adaptable to the screen width for different devices.

Bootstrap offers responsive float classes at your service for a better responsive web page design.

Basically, float utility classes provided by Bootstrap are based on the CSS floats property.

They can float the element to the left or to the right or even disable the floating.

So, before we move on to the Bootstrap features of float, let’s have a quick recap of CSS float property.

CSS Float Property

In CSS the float property is there for the layout on the web-pages.

This property can be real useful when you want to wrap any text around images.

The float property for the <img> can be set for one side and the rest of the content will be positioned accordingly.

The permissible values for this property are as follows:

  • left – The float element will float to the left of the container
  • right– The float element will float to the right of the container
  • none – No float value specified. The element will be displayed as per its position in the text. The default value for the property is set to none
  • inherit – Inherit the float value from the parent element

The code below will show the float property applied on an image:

Now, that we understand the basic working of float, let’s get back to Bootstrap and see what it has to offer.

Bootstrap Float Classes

Based on the permissible values of the CSS float property, we have three basic Bootstrap classes:

  • float-left
  • float-right
  • float-none

The working of this classes is similar to the what we read about the respective values. The code below give an example of each for better understanding:

Apart from this, there are other utitlity classes as well, that we’ll discuss in this chapter.

Bootstrap Mixins

You can also toggle the floats using the Sass mixins. See the code below:

Bootstrap Responsive classes

There are also available, responsive classes for the different float values. Check the code below:

Bootstrap Clearfix

Bootstrap float utility is very helpful in positioning the components properly on the web-page.

But there are is an issue in this approach that needs to be addressed. Check out the code below to know about the same:

If you load this code on a browser, you can observer following points:

  • A <div> is created with a green border and some text content in it
  • The <img> added to this <div> is made to float to the right of the div
  • The image is overflowing from the <div> component

The third point is the float issue we were talking about.

When you make any element to float, it might flow around its containing element.

This is bad for the styling on the web page as the components not look very neat.

To fix this problem we have special hack in Bootstrap called the ‘clearfix’ hack.

Here we will understand what the ‘Clearfix’ hack is and how it can help us to solve the problem we discussed before.

Bootstrap Clearfix Hack

Basically clearfix, clears the overflowing float component.

You can add the clearfix to the containing element (like the <div> in this case) and will contain the floating element withing itself so it doesn’t overflow.

The code below explains how you can use clearfix in CSS.

Based on this knowledge, we will understand how we can use clearfix in Bootstrap.

Now that, we have understood the basic working of a clearfix, let’s move to Bootstrap.

Bootstrap Clearfix Utilities

So, we know that Clearfix quickly and easily clears the floated content within a container.

The basic classe used for this is the .clearfix. This is used with the parent element.

<div class="clearfix">...</div>

You can also use clearfix with Mixins