Welcome to the sixth part of our Core Java series. In the last part, we discussed about Object Oriented Programming(OOPS). If you are new, please checkout the previous parts. In this part, we’ll discuss exceptional handling and some other interesting stuff in Java. So Let’s get started.


A package is known as a named collection of classes. The purpose of looping classes in a package is to make it easy to add the classes in a package into our program code. One aspect of this is that it allows us to avoid the interference of the names used for classes in one package with the names of classes in another package in our code because the class names in a package are qualified by the package name. It is like a folder in the directory which contains all the related classes to provide access protection. Every class in Java is contained within a package.

Types of Packages

  1. Build In Packages - which comes with the installation of Java. Some of the build-in packages in Java are - java.lang, java.io, java.swing, java.util

  2. User defined Packages - We can also create our own packages and put our compiled classes there. We can create it by using package statement.

  • To put a class in a User defined package, we just need to add a package statement as first statement in the source code containing the class definition.
package finance;
public class money{
  • It must always be the first statement. Only comments and blank lines can be used to precede the package statement.

To compile a Java program with package statements, we have to use -d option while running the javac command like this -

javac -d folder_name testfile.java

It’ll create a folder with the given name and put all the compiled classes in that.

  • If we want the classes in a package to be accessible outside the package, we must declare the class using a keyword public.

  • Any class that has not been declared as public, will not be accessible from outside the package.

  • A package name need not have a single name. It can be a sequence of names separated by periods(.)

package project.java.core;

Naming Conventions

Lower Case is used for package names to avoid conflict with the names of classes or interfaces. Build-in packages are begin with java or javax.

Adding classes from package to our program

We can add classes from a package using import statement.

import finance.money; // to add a single class import finance.*; // to add all the classes

  • When we import a package, only its classes are included in our program. Its inner and outer packages are not included. We need to import them explicitely.

Exceptional Handling

An exception usually signals an error. It can also signal some particular unusual event in our program that deserves special attention.

  • One major benefit of having an error signalled by an exception is that it separates the code which deals with errors from the code that is executed when things are moving along smoothly.

  • Another benefit of exceptions is that they provide a way of enforcing a responce to particular error with many kind of exceptions. We have to handle it in our code otherwise our code will not compile.

An exception object in Java is created when an abnormal situation arises in the program. This object has data members that store information about the nature of the problem. This exception object is throw by our program and is catched by a specific code.

Exception Hierarchy

Exceptions Hierarchy

There are two major types of exceptions in Java -

  1. Compile Time Exception/Checked Exceptions -

They are arised during the compilation of the program. They are standard method errors. It is mandatory to handle these exceptions otherwise our code will not compile. Examples - FileNotFoundException, SQLException, InterruptedException etc.

  1. Run time exception/Unchecked Exception -

They appears during the runtime of our program. During compilation of our program, we cannot notice them that’s why it is optional to handle them. Without handling them also we can compile and run our code. Examples - ArithmaticException, ArrayIndexOutOfBoundException etc.

  • We can also design and throw our own exceptions.

  • An exception is an object of sub-sub class of the standard class Throwable.

Let us see how we can handle exceptions in Java.

class A{
	public static void main(String args[]){

			// open file
			// read file
		catch(FileNotFoundException e){
			// code after catching the exception
		catch(EOFException e){
			// code after catching the exception
			// this code will always exceute

There are three main blocks of exception handling -

  1. try block - A try block encloses the code that may give rise to an exception. With try block we can either use catch or finally block.
try {
    code which can cause an exception
catch and finally blocks . . .
  1. catch block - A catch block contains the code that will be executed when an exception is thrown by try block. It should be always used with try block.
try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

  1. finally block - finally is optional. If provided, it will always execute.
  • We can use try-catch block, try-catch-finally block, and try-finally block.
  • In case of try-finally if exception occurs, our program will terminate but before termination finally block will execute.
  • If we are not going to handle an exception that can be generated in a method then we must declare it using throws clause while defining the method.
public void function() throws FileNotFoundException{
  • If another method calls this method, it too must take account of the exception either by handling it or by declaring that it can throw the exception as well.

Exception Methods

Following are some of the methods which can be used after handling the exception -

  1. getMessage() - returns a detailed description of the exception.
  2. getStackTrace() - returns an array containing each element of the stack trace.
  3. printStackTrace() - prints the stack trace to the error output stream.
  4. getCause() - returns the cause of the occurred exception
  5. toString() - returns a short description with name of the class of the exception.

Let’s see an example -

import java.util.*;
import java.lang.*;
import java.io.*;

class ExceptionExample
	public static void main (String[] args)
		try {
         int x = 11/0;
      } catch (ArithmeticException e) {
         System.err.println("Exception is caught");
         System.err.println("getMessage():" + e.getMessage());
         System.err.println("getLocalizedMessage():" + e.getLocalizedMessage());
         System.err.println("getCause():" + e.getCause());
         System.err.println("toString():" + e);

Output will be:

Exception is caught
getMessage():/ by zero
getLocalizedMessage():/ by zero
toString():java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
	at Ideone.main(Main.java:13)

throw and throws

  • throw is used to explicitely throw an exception whereas throws is used to declare an exception.
  • throw is followed by an instance of that particular exception whereas throws is followed by an exceltion class name.
  • We can throw only one exception at a time using throw but with throws we can declare multiple exceptions by separating them with comma.
  • throw cannot handle checked exceptions like IOException, SQLException etc. but throws can be used to handle them.

Example -

public void method() 
   //throwing an exception
   throw new ArithmeticException("Check your calculation");
public static void method( ) throws FileNotFoundException {

That’s all for now. Now it’s your turn to try what you learned in this blog. Happy Coding :)