Exception Handling in Java

 Exception Handling

One of the most important features of java programming is exception handling, which allows us to handle runtime errors caused by exceptions. We will learn what an exception is, the different sorts of exceptions, exception classes, and how to manage exceptions in Java using examples 

What is an exception ?

An exception is an unintended event that interrupts the program's normal flow. When a programs detects an exception, it is terminated. In such cases, we receive an error message generated by the system. Exceptions are useful because they can be handled in Java. We may provide a meaningful message to the user about the issue instead of a system produced message, which may not be clear to a user, by managing exceptions.

Exception Handling in Java
exception handling in java


Why an exception occurs ?

There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, bad input data provided by user etc.

Why use Exception handling?

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java.

Error vs exception :

Error : indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error.

Exception :are events that occurs in the code. A programmer can handle such conditions and take necessary corrective actions.

Hierarchy of Java Exception classes :

Hierarchy of Java Exception classes
Hierarchy of Java Exception classes

{tocify} $title={Table of Contents}

Types of exceptions :

1. Checked Exceptions :

Checked exceptions are all exceptions other than Runtime Exceptions that the compiler checks during compilation to verify if the programmer has handled them or not. Compilation errors will occur if these exceptions are not handled/declared in the code. SQLException, IOException, ClassNotFoundException, and so on.

2. Unchecked Exceptions :

Unchecked Exceptions are also name for Runtime Exceptions. These exceptions are not checked at compilation time, thus the compiler has no way to know whether the programmer has handled with them or not. It is the programmer's responsibility to deal with these exceptions and provide a safe exit. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, and other exceptions are examples.

Java Exception Keywords :

try : 

  • The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch blocks or finally block or both.

catch : 

  • The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.

finally : 

  • A finally block contains all the crucial statements that must be executed whether exception occurs or not. The statements present in this block will always execute regardless of whether exception occurs in try block or not such as closing a connection, stream etc.

throw :  

  • The "throw" keyword is used to throw an exception.

throws : 

  • unchecked exception (Runtime) doesn’t get checked during compilation. Throws keyword is used for handling checked exceptions . By using throws we can declare multiple exceptions in one go.

Exception Handling Example :

class Test 
{
public static void main(String args[])
{
int num1, num2;
try {
/* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e)
{
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
System.out.println("You should not divide a number by zero");
}
catch (Exception e)
{
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I am out of try-catch block in Java.");
}
}

Output :
You should not divide a number by zero
I am out of try-catch block in Java.


frequently used exceptions : 


Arithmetic exception: 

If we divide any number by zero, there occurs an ArithmeticException. Class: Java.lang.ArithmeticException This is a built-in-class present in java.lang package. This exception occurs when an integer is divided by zero.

class ExampleClass 
{
public static void main(String args[])
{
try
{
int a = 30, b = 0;
int output = a / b;
System.out.println("Result: " + output);
}
catch (ArithmeticException e)
{
System.out.println("You Should not divide a number by zero");
}
}
}

Output :
You Should not divide a number by zero

NullPointer Exception :

If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.

class Test 
{
public static void main(String args[])
{
try{
String str=null;
System.out.println (str.length());
}
catch(NullPointerException e){
System.out.println("NullPointerException..");
}
}
}

Output :
NullPointerException..


NumberFormatException :

This exception occurs when a string is parsed to any numeric variable.Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException.
class Test
{
public static void main(String args[])
{
try{
int num=Integer.parseInt ("ABC") ;
System.out.println(num);
}catch(NumberFormatException e){
System.out.println("Number format exception occurred");
}
}
}

Output :
Number format exception occurred


ArrayIndexOutOfBoundsException :

This exception occurs when you try to access the array index which does not exist. For example, If array is having only 5 elements and we are trying to display 7th element then it would throw this exception.

class Test
{
public static void main(String args[])
{
try{
int arr[]=new int[10];
//Array has only 10 elements
arr[11] = 9;
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("ArrayIndexOutOfBounds");
}
}
}

Output :
ArrayIndexOutOfBounds


StringIndexOutOfBound :

An object of this class gets created whenever an index is invoked of a string, which is not in the range.

class Test
{
public static void main(String args[])
{
try{
String str="abcd";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}

Output :
4
StringIndexOutOfBoundsException!!


Tech Smart

Hello, my name is Sam and I am the blog's author. I enjoy blogging since I am passionate about it and I am an enthusiastic learner. Blogging provides me a greater platform to share all of my knowledge and experiences with my readers.

Post a Comment

if you have any doubts, Please let me know

Previous Post Next Post