Chapter 3 Exception Handling

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 32

Exception handling in Java

Errors in program

• Errors are most of the time part of software development even for a
seasoned developers.
• There are basically 3 types of errors
• 1. compile time error-
• 2. Runtime error- this error represents inefficency of the computer
system to execute particular statement
• 3. Logical error-
o Boolean b;b++;- operator can’t be applied
o Int I=1233333;- incompatible type
o Losing precision
Exception handling

o The Exception Handling in Java is one of the powerful mechanism to handle


the runtime errors so that normal flow of the application can be maintained.
o Exception is an abnormal condition.
o In java it is an object which is thrown at runtime.
Exception handling

• Some exceptions that can be detected by compiler at compile time-


checked exceptions.
o Ex: file not found
o IOException, SQLException, ClassNotFoundException

• Detected by JVM are unchecked Exceptions


o NullPointerException
o ArrayIndexOutOfBoundsException
o ArithmeticException
Advantage of Exception Handling
Let's take a scenario:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of
the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling,
the rest of the statement will be executed. That is why we use exception handling in Java.
Hierarchy of Exception classes
Types of exception
• There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked
exception.
According to Oracle, there are three types of exceptions:
1) Checked Exception
The classes which directly inherit Throwable class except Runtime Exception and Error are known as checked exceptions e.g.
IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but
they are checked at runtime.

3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should


place exception code. The try block must be followed by either
catch or finally. It means, we can't use try block alone.

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 The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.

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

throws The "throws" keyword is used to declare exceptions. It doesn't


throw an exception. It specifies that there may occur an
exception in the method. It is always used with method
signature.
Java Exception Handling Example

Let's see an example of Java Exception Handling where we using a try-catch statement to handle the exception.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...rest of the code...
Common Scenarios of Java Exceptions Example
There are given some scenarios where unchecked exceptions may occur. They are as
follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
Common Scenarios of Java Exceptions Example
3) A scenario where NumberFormatException occurs
The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that has characters,
converting this variable into digit will occur
NumberFormatException.

String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException
Java try-catch block

Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
If an exception occurs at the particular statement of try block, the rest of the block code will not
execute. So, it is recommended not to keeping the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.

try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

try{
//code that may throw an exception
}finally{}
Java catch block

• Java catch block is used to handle the Exception by declaring the type
of exception within the parameter. The declared exception must be the
parent class exception ( i.e., Exception) or the generated exception
type. However, the good approach is to declare the generated type of
exception.
• The catch block must be used after the try block only. You can use
multiple catch block with a single try block.
Internal working of java try-catch block
Java try-catch block example

public class TryCatchExample2 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}

Output:
java.lang.ArithmeticException: / by zero
rest of the code
Java try-catch block example

public class TryCatchExample3 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
Output:
java.lang.ArithmeticException: / by zero
Java try-catch block example

An example to print a custom message on exception.


public class TryCatchExample5 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println("Can't divided by zero");
}
}
}
Output :
Can't divided by zero
Java try-catch block example

An example to print a custom message on exception.


public class TryCatchExample5 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println("Can't divided by zero");
}
}
}
Output :
Can't divided by zero
Java try-catch block example

public class TryCatchExample5 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println("Can't divided by zero");
}
}
}
Output :
Can't divided by zero
Java try-catch block example

An example to resolve an exception in catch block.


public class TryCatchExample6 {

public static void main(String[] args) {


int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
Output:
25
Java try-catch block example

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class TryCatchExample10 {

public static void main(String[] args) {


PrintWriter pw;
try {
pw = new PrintWriter("jtp.txt"); //may throw exception
pw.println("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {
System.out.println(e);
}
System.out.println("File saved successfully");
}
}

Output:
File saved successfully
Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform
different tasks at the occurrence of different exceptions, use java multi-
catch block.
Points to remember
• At a time only one exception occurs and at a time only one catch block
is executed.
• All catch blocks must be ordered from most specific to most general,
i.e. catch for ArithmeticException must come before catch for
Exception.
Java Multi-catch block

public class MultipleCatchBlock1 {


public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Java nested Try-catch blocks

class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}
finally block in exception handling

• Java finally block is a block that is used to execute important code such
as closing connection, stream etc.
• Java finally block is always executed whether exception is handled or
not.
• Java finally block follows try or catch block.
• If you don't handle exception, before terminating the program, JVM
executes finally block(if any).
• For each try block there can be zero or more catch blocks, but only one
finally block.
Java throw exception

• The Java throw keyword is used to explicitly throw an exception.


• We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom
exception. We will see custom exceptions later.
• The syntax of java throw keyword is given below.
throw new IOException("sorry device error);
Java throw keyword example
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Java throw keyword example
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Java Exception propagation
An exception is first thrown from the top of the stack and if it is not
caught, it drops down the call stack to the previous method,If not caught
there, the exception again drops down to the previous method, and so on
until they are caught or until they reach the very bottom of the call
stack.This is called exception propagation.
Java Exception propagation
class TestExceptionPropagation1{
void m(){
int data=50/0;
}
void n(){
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
Java throws keyword
• The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to
provide the exception handling code so that normal flow can be maintained.
• Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is
not performing check up before the code being used.
return_type method_name() throws exception_class_name{
//method code
}
Advantage of Java throws keyword
• Now Checked Exception can be propagated (forwarded in call stack).
• It provides information to the caller of the method about the exception.
Difference between throw and throws in Java
No. throw throws
1) Java throw keyword is used to Java throws keyword is used to
explicitly throw an exception. declare an exception.

2) Checked exception cannot be Checked exception can be propagated


propagated using throw only. with throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method
signature.
5) You cannot throw multiple You can declare multiple exceptions
exceptions. e.g.
public void method()throws
IOException,SQLException.

You might also like