Geek Culture
Published in

Geek Culture

Exception Handling in Java

Exception: An exception in java is an unwanted event that occurs and disrupts the normal flow of the program. These are recoverable. A programmer can handle such conditions and take necessary corrective actions. Some of them are NullPointerException, SQLException, ClassNotFoundException and RuntimeException. For example, a number divide by zero is a type of RuntimeException.

public class Example {
public static void main(String[] args){
int num1 = 100;
int num2 = 0;
int result = num1 / num2;
}
}
Output: java.lang.ArithmeticException: / by zero
at Example.main(Example.java:5)

Error: It is a problem that occurs mainly due to the lack of system resource. These are non-recoverable. Some of them are StackOverflowError, VirtualMachineError and OutofMemoryError. For example, StackOverflow Error is an infinite recursive error, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack.

public class Example {
public static void main(String[] args){
recursiveMethod();
}
public static void recursiveMethod(){
while(true){
recursiveMethod();
}
}
}
Output: Exception in thread "main" java.lang.StackOverflowError
at ErrorExample.recursiveMethod(Main.java:7)
at ErrorExample.recursiveMethod(Main.java:7)
at ErrorExample.recursiveMethod(Main.java:7)
at ErrorExample.recursiveMethod(Main.java:7)
.
.
.

Exception Handling: It is the mechanism to handle runtime error so that the normal flow of the application can be maintained. An exception normally disrupts the normal flow of the program that is why we use exception handling.

Exception Hierarchy in java

There are two types of exceptions in java :

  1. Checked Exception: These exceptions are checked at compile time to see whether the programmer has handled them or not. If these exceptions are not handled in the program, you will get a compilation error. For example, SQLException, IOException, ClassNotFoundException etc.
  2. Unchecked Exception: These exceptions are checked at runtime, so it is the responsibility of the programmer to handle these exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

try block: It is a block that consists of statements where the exceptions are likely to occur. A try block is always followed by a catch block where these exceptions are handled. A try block must be followed by catch blocks or finally block or both.

try{
//statements that may cause an exception
}

catch block: It is a block to handle the exceptions that are occurred in the try block. When an exception occurs in the try block, the catch block that handles that particular exception executes.

try
{
//statements that may cause an exception
}
catch (Exception(type) e(object))‏
{
//error handling code
}
class Solution{
public static void main(String args[]){
int num1 = 10;
int num2 = 0;
try{
System.out.println("Statement 1");
System.out.println("Statement 2");
int result = num1 / num2;
System.out.println("Statement 4")
}catch(ArithmeticException e){
System.out.println("Number divide by Zero");
}
}
}
Output: Statement 1
Statement 2
Number divide by Zero

In the above example, when a number is divided by zero, an ArithmeticException occurred caught by the catch block. The block of code after the statement where the exception occurred will never be executed.

finally block: It is a block that will be definitely executed whether an exception has occurred or not.

try {
//Statements that may cause an exception
}
catch(Exception(type) object) {
//Handling exception
}
finally {
//Statements to be executed
}
class Solution{
public static void main(String args[]){
int num1 = 10;
int num2 = 0;
try{
int result = num1 / num2;
}catch(ArithmeticException e){
System.out.println("Number divide by Zero");
}
finally{
System.out.println("finally block is executed");
}
}
}
Output : Number divide by Zero
finally block is executed

throw: It is a keyword that is used to throw our own customised exception. Suppose if you want to make a program that allows the people to vote in the election if they are 18 or above. Then we can use the throw keyword to throw our own customized exception that if the age of a person is under 18, it will show “You are not allowed to vote”.

class Solution{
public static void main(String args[]){
int personAge1 = 18;
int personAge2 = 15;
checkEligibility(personAge1);
checkEligibility(personAge2);
}

static void checkEligibility(int age){
if(age < 18){
throw new ArithmeticException("You are not allowed to vote");
}
else {
System.out.println("You are allowed to vote");
}
}
}
Output: Exception in thread "main" java.lang.ArithmeticException: You are not allowed to vote
at Solution.checkEligibility(Main.java:10)
at Solution.main(Main.java:12)

throws: It is mainly used to declare an exception. It tells the programmer that there might be a chance of occurring an exception so it is better to provide the exception handling code to maintain the flow to the program.

public void myMethod() throws ArithmeticException{
// Statements that might throw an exception
}

public static void main(String args[]) {
try {
myMethod();
}
catch (ArithmeticException e) {
// Exception handling statements
}
catch (NullPointerException e) {
// Exception handling statements
}
}

Example :

class M{  
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{
M m=new M();
m.method();

System.out.println("normal flow...");
}
}
Output: Exception in thread "main" java.io.IOException: device error
at M.method(Main.java:10)
at Testthrows4.main(Main.java:16)

--

--

--

A new tech publication by Start it up (https://medium.com/swlh).

Recommended from Medium

Building a disaster recovery site on AWS for workloads on GCP —  (Part 2)

So You Want to Make a Personal Website

Managing Elevated Access in Snowflake — Just Enough, Just-in-Time

Coding for beginners: a manual to start in programming languages.

Corral Your Database Changes

[EN] 10/20(Wed) update notice

What the F(#)?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Akshay Tomar

Akshay Tomar

More from Medium

Java: Exception Handling

Code structure in Java

How to Build Java Applications Today #60

Singleton Design pattern in Java