You are on page 1of 33

Exception Handling

Dr. L.M. Jenila Livingston


VIT Chennai
Introduction
• An exception is an abnormal code or event that breaks the
regular flow of the code in programming terms
• Such exceptions require specific programming constructs for
its execution
• Exception handing is a process or method used for handling
the anomalous statements in the code and executing them is
termed as exception handling
• For example, the Division of a non-zero value with zero will
result into infinity always.
• Other examples: ClassNotFoundException, IOException (read
in a file that does not exist), SQLException etc.

Dr. L.M. Jenila Livingston 2


1. statement 1;
Exception
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5; //exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

If 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.

Dr. L.M. Jenila Livingston 3


Types of Errors
• There are three types of errors in the code:
• Syntax Error: A syntax error may appear if there is any mistake
in the pre-defined syntax of a programming language.
• Runtime Error: When an error occurs during the execution of
the program, such an error is known as Runtime error. The
codes which create runtime errors are known as Exceptions.
Thus, exception handlers are used for handling runtime
errors.
• Logical Error: Logical mistake in the program that may not
produce the desired output, and may terminate unusually.

Dr. L.M. Jenila Livingston 4


Dr. L.M. Jenila Livingston 5
6
Run time exceptions - Examples
1. int a=1000/0;//ArithmeticException
2. String s=null;
System.out.println(s.length());//NullPointerException
3. String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4. int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsExceptio

Dr. L.M. Jenila Livingston 7


Dr. L.M. Jenila Livingston 8
Exception Handling keywords
Keyword Description
try • The try keyword -test a block of code for errors. It passes control to the
catch{} block for taking suitable actions and handle the error in case any
error occurs. Otherwise, it executes the code written within
• We can't use try block alone. The try block must be followed by either
catch or finally.
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 necessary code of the program
(execute code, after try and catch).
• It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception. The throw statement -
create custom errors or user-defined errors .
throws The "throws" keyword is used to declare exceptions. It specifies that there
may occur an exception in the method.
It doesn't throw an exception. It is always used with method signature.

Dr. L.M. Jenila Livingston 9


Dr. L.M. Jenila Livingston 10
Syntax
try {
// block of code to monitor for errors 11

}
catch (Exception Type1 exob) {
// exception handler for Exception Type1
}
catch (Exception Type1 exob) {
// exception handler for Exception Type1
}
// …
finally {
// block of code to be executed before try block ends
}
Code without exception handling
public class JavaExceptionExample{
public static void main(String args[]){
int data=100/0;
int A=10, B=5;
System.out.println(A+B);
System.out.println("Code successfully executed");
}
}

Dr. L.M. Jenila Livingston 12


Example 1:
public class JavaExceptionExample{
public static void main(String args[]){
try{
int data=100/0;
}
catch(ArithmeticException e)
{System.out.println(e);}
System.out.println("rest of the code...");
int A=10, B=5;
System.out.println(A+B);
System.out.println("Code successfully executed");
}
}
Dr. L.M. Jenila Livingston 13
Example
public class TryCatchExample4 {
2:
public static void main(String[] args) {
try{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{System.out.println(e);}
System.out.println("rest of the code...");
int A=10, B=5;
System.out.println(A+B);
System.out.println("Code successfully executed");
}

}
Dr. L.M. Jenila Livingston 14
public class MultipleCatchBlock2 { Example 3: Multiple catch
public static void main(String[] args) {

try{
int a[]=new int[5];

System.out.println(a[10]);
}
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");
}
}
Dr. L.M. Jenila Livingston 15
//main try block
try { Nested try
statement 1;
statement 2;
//try catch block within another try block
try {
statement 3;
statement 4;
//try catch block within nested try block
try {
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
} Dr. L.M. Jenila Livingston 16
Example 4: Nested try
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}

Dr. L.M. Jenila Livingston 17


finally statement
• An optional block of statements which is executed
after the execution of try and catch statements
• Finally block does not hold for the exception to be
thrown
• Any exception is thrown or not, finally block code, if
present, will definitely execute. It does not care for
the output too.
• Therefore, we can also use try/throw/catch/finally
keyword together for handling complex code.

Dr. L.M. Jenila Livingston 18


Example 5: finally
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}

System.out.println("rest of phe code...");


}
}
Dr. L.M. Jenila Livingston 19
throw syntax
try{
throw exception; // user can define their own exception
}
catch(error) {
expression; } // code for handling exception.

• The exception can be a string, number, object, or boolean


value
• With the help of throw statement, users can create their
own errors

Dr. L.M. Jenila Livingston 20


throw
public class Example6{
void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not Eligible for
voting");
else System.out.println("Eligible for voting"); }

public static void main(String args[]){


Example6 obj = new Example6();
obj.checkAge(13);
System.out.println("End Of Program");
} }

Dr. L.M. Jenila Livingston 21


throw
//throw exception: user can define their own exception

public class Example7 {


static void checkEligibilty(int age, int weight){
if(age<12 && weight<40)
{
throw new ArithmeticException("Student is not eligible
for registration");
}
else {
System.out.println("Student Entry is Valid!!");
} }

public static void main(String args[]){


System.out.println("Welcome to the Registration process!!");
checkEligibilty(10, 39);
System.out.println("Have a nice day..");
} }

Dr. L.M. Jenila Livingston 22


throws
type method (arguments) throws Exception
{
throw exception; // user can define their own exception
}

try
{
}
Catch
{
}
Dr. L.M. Jenila Livingston 23
throws
public class Example8{
int division(int a, int b)
throws ArithmeticException
{
int t = a/b; return t; }

public static void main(String args[]){


Example8 obj = new Example8();
try{
System.out.println(obj.division(15,0));
}
catch(ArithmeticException e){
System.out.println("You shouldn't divide
number by zero");
}} }
Dr. L.M. Jenila Livingston 24
throw and throws
throw throws
Used to explicitly throw Used to declare an exception.
an exception - indicate what exception type
-used within a method may be thrown by a method
or block of code - used with a method signature
Cannot throw multiple Can declare multiple
exceptions exceptions
•Syntax: throw is •Syntax: throws is followed by
followed by new type a class
•used inside the method •and used with the method
signature
Dr. L.M. Jenila Livingston 25
throws and throw
type method (arguments) throws Exception
{
throw exception; // user can define their own exception
}

Dr. L.M. Jenila Livingston 26


throws and throw
public class Main {
static void checkAge(int age) throws ArithmeticException {

if (age < 18) {


throw new ArithmeticException("Access denied - You must be
at least 18 years old."); }
else {
System.out.println("Access granted - You are old enough!");
} }

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
} }

Dr. L.M. Jenila Livingston 27


throws and throw
The method removes the top element from the stack and
returns the object:
Public Object pop() throws EmptyStackException {
Object obj;
if (top == 0) {
throw new EmptyStackException();
}
obj = objectAt(top - 1);
setObjectAt(top - 1, null);
top--;
return obj;
}

Dr. L.M. Jenila Livingston 28


try…catch…throws..throw syntax
type method (arguments) throws Exception1, Exception2,
…{
throw exception; // user can define their own exception
}

try{
}
catch(error) {
expression; } // code for handling exception.

Dr. L.M. Jenila Livingston 29


try…catch…throws..throw
import java.io.*;
class Example {
void myMethod(int num)throws IOException, ClassNotFoundException
{ if(num==1)
throw new IOException("IOException Occurred");
else
throw new ClassNotFoundException("ClassNotFoundException");
}}
public class Example10{
public static void main(String args[]){
try{
Example obj=new Example();
obj.myMethod(1); }
catch(Exception ex)
{
System.out.println(ex);
}}
}
Dr. L.M. Jenila Livingston 30
3 Ways to print exception messages

Method Description
printStackTrace() It print the name of the exception,
description and complete stack trace
including the line where exception occurred.
toString() It prints the name and description of the
exception.
getMessage() Mostly used. It prints the description of the
exception.

Dr. L.M. Jenila Livingston 31


public class Tester {
public static void main(String args[]) {
try {
int result = 10/0;
System.out.println(result); }
catch(Exception e) {
System.out.println(e)l
System.out.println("toString(): " + e.toString());
System.out.println("getMessage(): " + e.getMessage());
System.out.println("StackTrace:");
e.printStackTrace();
}
}}

32
References
• https://www.javatpoint.com/exception-
handling-in-java
• https://www.tutorialspoint.com/java/java_exc
eptions.htm

Dr. L.M. Jenila Livingston 33

You might also like