Welcome to the sixth part of our Core Java series. In the last part, we discussed Object Oriented Programming(OOPS). If you are new, please check out the previous articles. Here we’ll discuss exceptional handling and some other interesting stuff in Java. Let’s get started.
A package is a named collection of classes. The purpose of looping classes in a package is to make it easy to add them 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.
Build-in packages - come with the installation of Java. Some of the build-in packages in Java are java.lang, java.io, java.swing, and java.util.
User defined packages - packages that hold our compiled classes, created by us using a package
statement.
To put a class in a user defined package, we just need to add a package
statement as the first statement in the source code containing the class definition.
1 2 3 4
package finance; public class money { ... }
The ‘package’ statement 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
This will 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 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;
Lower case is used for package names to avoid conflict with the names of classes or interfaces. Build-in packages begin with java
or javax
.
We can add classes from a package using an import
statement.
// to add a single class
// 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 explicitly.
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 response to a particular error with many kinds 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 thrown by our program and is caught by a specific code.
There are two major types of exceptions in Java.
Compile time exception/checked exceptions
They arise 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…
Runtime exception/unchecked exception
These appear during the runtime of our program. During compilation of our program, we will not notice them, which is why it is optional to handle them. Without handling them we can still compile and run our code. Examples - ArithmaticException, ArrayIndexOutOfBoundException etc.
We can design and throw our own exceptions.
An exception is an object of the sub-sub class of the standard class Throwable
.
Let us see how we can handle exceptions in Java.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class A {
public static void main(String args[]) {
...
...
...
try {
// open file
// read file
} catch (FileNotFoundException e) {
// code after catching the exception
} catch (EOFException e) {
// code after catching the exception
} finally {
// this code will always exceute
}
}
}
There are three main blocks of exception handling.
try
block - A try block encloses the code that may give rise to an exception. With a try block we can either use catch
or finally
block.
1 2 3 4
try { code which can cause an exception } catch and finally blocks...
catch
block - A catch block contains the code that will be executed when an exception is thrown by try block. It should always be used with a try block.
1 2 3 4 5 6 7
try { } catch (ExceptionType name) { } catch (ExceptionType name) { }
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 an 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 the throws
clause while defining the method.
1
2
3
4
5
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.
Following are some of the methods which can be used after handling the exception -
getMessage() - returns a detailed description of the exception.
getStackTrace() - returns an array containing each element of the stack trace.
printStackTrace() - prints the stack trace to the error output stream.
getCause() - returns the cause of the occurred exception.
toString() - returns a short description with the name of the class of the exception.
Let’s see an example -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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);
System.err.println("printStackTrace():");
e.printStackTrace();
}
}
}
Output will be:
1
2
3
4
5
6
7
8
Exception is caught
getMessage(): / by zero
getLocalizedMessage(): / by zero
getcause(): null
toString(): java.lang.ArithmeticException: / by zero
printStackTrace():
java.lang.ArithmeticException: / by zero
at Ideone.main(Main.java: 13)
throw
is used to explicitly 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 exception 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 -
1
2
3
4
public void method() {
//throwing an exception
throw new ArithmeticException("Check your calculation");
}
1
2
3
public static void method() throws FileNotFoundException {
//code
}
That’s all for now. Now it’s your turn to try what you learned in this blog post. Happy Coding :)