Exception Handling in Java

Understanding Exceptions in Java

Thathsara Pramodhi
LinkIT
4 min readJun 7, 2020

--

Photo by Caspar Camille Rubin on Unsplash

From this article, I would like to talk about Exception Handling in Java. I hope you can get a perfect idea about Java exceptions after reading this article.

What is an Exception?

An exception is an unwanted or unexpected event, which arises during the execution of a program. When an exception occurs the normal flow of the program is terminated. Therefore these exceptions are to be handled.

Exception Hierarchy

Image from BenchResources.Net

Exception and error types are subclasses of the Throwable class. Errors can’t be handled by the developer but, exceptions can be handled by the developer. Mainly exceptions have 2 types. Such as checked exception (compile-time exception) and unchecked exception ( runtime exception).

Java Exception Handling Keywords

There are 5 keywords used in Java exception handling.

  1. try - the exception prone statement, we put it within a try block. try keyword does not appear without a catch or finally keyword.
  2. catch - this block is used to handle the exception. We can’t use catch block alone. We should have a try block before the catch block.
  3. finally - this is used to execute an important code of the program whether the exception was handled or not. We can use finally block instead of a catch block.
  4. throw - this keyword is used to throw an exception. It can’t throw compile-time exceptions.
  5. throws - this is used to declare an exception. It doesn’t throw an exception. This is used with the method signature.

try-catch Clause

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

If we think because of some kind of statement in the code, it will terminate the whole program, there we can use the try-catch block. The code within the try-catch block act as a protected code. Every try block should be immediately followed either by a catch block or finally block.

In the following code, we didn’t use any exception handling. But an exception arises.

public class Demo {
public static void main(String[] args) {
A();
}
static void A() {
System.out.println("Start A");
B();
System.out.println("End A");
}
static void B() {
System.out.println("Start B");
C();
System.out.println("End B");
}
static void C() {
System.out.println("Start C");
int x = 10 / 0;
System.out.println("End C");
}
}

Output

Start A
Exception in thread "main" java.lang.ArithmeticException: / by zero
Start B
Start C

The exception in method C is checked from method B and method A and finally the main method by JVM. If that exception is not been handled then the program will terminate. When we use try-catch, the program is not terminated.

public class Demo {
static void A() {
System.out.println("Start A");
B();
System.out.println("End A");
}
static void B() {
System.out.println("Start B");
C();
System.out.println("End B");
}
static void C() {
System.out.println("Start C");
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println(e);
}

System.out.println("End C");
}

public static void main(String[] args) {
System.out.println("Start Main");
A();
System.out.println("End Main");
}
}

Output

Start Main
Start A
Start B
Start C
java.lang.ArithmeticException: / by zero
End C
End B
End A
End Main

Also, we can use multiple catch blocks as well. We can use any number of catch blocks after a single try.

public class Demo {
public static void main(String[] args) {
System.out.println("Start");
int x=4,y=4,z=0;
String name="abcd";
int[] xr= new int[4];
try{
xr[x]=name.charAt(y)/z;
}catch (StringIndexOutOfBoundsException e){
System.out.println(e);
}catch (ArithmeticException e){
System.out.println(e);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
System.out.println("End. ");
}
}

Output

Start
java.lang.StringIndexOutOfBoundsException: String index out of range: 4
End.

finally block

finally block doesn’t concern what happens in the protected code. finally block is put at the end of a try or catch block.

public class Demo {
public static void main(String[] args) {
System.out.println("Start");
int x=4,y=5,z=0;
String name="abcd";
int[] xr= new int[4];

try{
xr[x]=name.charAt(y)/2;
}catch (StringIndexOutOfBoundsException e){
System.out.println(e);
}catch (RuntimeException e){
System.out.println("ok");
System.out.println(e);
}catch (Exception e){
System.out.println(e);
}finally {
System.out.println("Finally");
}
System.out.println("End. ");
}
}

Output

Start
java.lang.StringIndexOutOfBoundsException: String index out of range: 5
Finally
End.

throws clause

When an exception is not handled, a method can declare the exception with the “throws” clause. When marked as throws, the calling methods have to handle the exception or declare to throw the same.

class Demo {
public static void main(String[] args)throws InterruptedException {
Thread.sleep(10000);
System.out.println("Hello Java!");
}
}

In the above program, we are getting a compile-time error because there can be an exception if the main thread is going to sleep, other threads get the chance to execute the main() method which will cause InterruptedException. Therefore we can use the “throws” keyword to handle the InterruptedException.

Output

Hello Java!

We can use the “throws” keyword for the checked exceptions. With the help of the “throws” keyword, we can give information to the caller of the method regarding the exception.

Handling the exception is very important in programming. Therefore I hope my article will help to you refresh your memory.

References

https://www.benchresources.net/interview-question-and-answer-on-exception-handling-in-java/

--

--