0% found this document useful (0 votes)
13 views

Chapter Four

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Chapter Four

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

College of Computing && Informatics

Department of Information Technology

Chapter-Four

Exception Handling
Compiled By Minichil A.
1
Exception Handling

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


 Exception handling is one of the most important feature of java programming that allows us to handle the

runtime errors caused by exceptions


 What is an exception?

 An Exception is an unwanted event that interrupts the normal flow of the program

 When an exception occurs program execution gets terminated. In such cases we get a system generated

error message
 The good thing about exceptions is that they can be handled in Java

 By handling the exceptions we can provide a meaningful message to the user about the issue rather than a

system generated message, which may not be understandable to a user.


2
Cont..
 Advantage of Exception Handling

 Exception handling ensures that the flow of the program doesn’t break when an

exception occurs
 Exception normally disrupts the normal flow of the application that is

why we use exception handling.


 Types of Exception

 There are two types of exceptions in Java:

1. Checked exceptions

2. Unchecked exceptions
3
Cont..
 Checked exceptions

 All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks

them during compilation to see whether the programmer has handled them or not.
 If these exceptions are not handled/declared in the program, you will get compilation error

 For example, SQLException, IOException, ClassNotFoundException etc.

 Unchecked Exceptions

 Runtime Exceptions are also known as Unchecked Exceptions.

 These exceptions are not checked at compile time so compiler does not check whether the programmer

has handled them or not


 It’s the responsibility of the programmer to handle these exceptions and provide a safe exit

 For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc


4
Cont…

5
Cont..
 Common Scenarios of Java Exceptions

 There are given some scenarios where unchecked exceptions may occur. They are as follows

A scenario where ArithmeticException Occurs


 If we divide any number by zero, there occurs an ArithmeticException

int a = 12 / 0; // ArithmeticException

A scenario where NullPointerException occurs


 If we have a null value in any variable, performing any operation on the variable leads to a

NullPointerException

String s = null;
System.out.println(length); NullPointerException

6
Cont..
A scenario where NumberFormatException Occurs
 If the formatting of any variable or number is mismatched. It may result into NumberFormatException

 Suppose we have a string variable that has characters, converting this variable into digit will cause

NumberFormatException
String s = “abc”;
int i = integer.parseint(s); // NumberFormatException

A scenario where ArrayIndexOutOfException occurs


 When an array exceeds to its size, ArrayIndexOutOfException occurs.

int a[] = new int [5];


a[10] = 50; // ArrayIndexOutOfException

7
Try Catch in Java – Exception handling

 Try block
 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
 Syntax of try block

try{
//statements that may cause an exception
}
 While writing a program, if you think that certain statements in a program can throw an exception,

8 enclosed them in try block and handle that exception


Catch block
 A catch block is where you handle the exceptions, and this block must follow the try block

 A single try block can have several catch blocks associated with it.

 You can catch different exceptions in different catch blocks.

 When an exception occurs in try block, the corresponding catch block that handles that particular exception executes

 Syntax of try catch in java

try
{
//statements that may cause an exception
}
catch (exception(type) e(object
{
//error handling code
9
}
Example: try catch block

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

 The example we seen above is having multiple catch blocks, lets see few rules about multiple catch

blocks

1. A single try block can have any number of catch blocks.

2. A generic catch block can handle all the exceptions, Whether it is ArrayIndexOutOfBoundsException
or ArithmeticException or NullPointerException or any other type of exception, this handles all of
them
catch(Exception e){
//This catch block catches all the exceptions
}

3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception:
11
5. You can also throw exception,
Catching multiple exceptions

 Lets take an example to understand how to handle multiple exceptions.

class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[4]=30/0;
 In the following example, the first catch block got executed because System.out.println("Last Statement of try block");
the code we have written in try block throws ArithmeticException }
(because we divided the number by zero). catch(ArithmeticException e){
System.out.println("You should not divide a
number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements
outside of the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
Output: System.out.println("Out of the try-catch block");
You should not divide a number by zero }
12 Out of the try-catch block }
 Now lets change the code a little bit and see the change in output:

 In this case, the second catch block got executed because the code class Example{
public static void main(String args[]){
throws ArrayIndexOutOfBoundsException. We are trying to access the try{
11th element of array in above program but the array size is only 7. int arr[]=new int[7];
arr[10]=10/5;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a
number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements
outside of the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
Output: System.out.println("Out of the try-catch block");
Accessing array elements outside of the limit }
Out of the try-catch block }
13
Java Finally block – Exception handling

 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. class Example


{
 Syntax of Finally block public static void main(String args[]) {
try{
int num=121/0;
try { System.out.println(num);
//Statements that may cause an exception }
} catch(ArithmeticException e){
catch { System.out.println("Number should not be divided by
zero");
//Handling exception }
} /* Finally block will always execute
finally { * even if there is no exception in try block
//Statements to be executed */
} finally{
System.out.println("This is finally block");
}
Output:
System.out.println("Out of try-catch-finally");
Number should not be divided by zero }
This is finally block }
14 Out of try-catch-finally
cont..
 Few Important points regarding finally block

 A finally block must be associated with a try block, you cannot use finally without a try block. You

should place those statements in this block that must be executed always
 Finally block is optional, as we have seen in previous examples that a try-catch block is sufficient for

exception handling, however if you place a finally block then it will always run after the execution of
try block.
 In normal case when there is no exception in try block then the finally block is executed after try

block. However if an exception occurs then the catch block is executed before finally block
 An exception in the finally block, behaves exactly like any other exception

 The statements present in the finally block execute even if the try block contains control transfer

statements like return, break or continue.

15
Another example of finally block and return statement
 You can see that even though we have return statement in the method, the finally block
still runs.
class JavaFinally
{
public static void main(String args[])
{
System.out.println(JavaFinally.myMethod());
}
public static int myMethod()
{ Output:
try { This is Finally block
return 112; Finally block run even after return statement
} 112
finally {
System.out.println("This is Finally block");
System.out.println("Finally block run even
after return statement");
}
}
16 }
Java throw keyword
 The Java throw keyword is used to explicitly throw an exception

 The throw keyword is mainly used to throw custom exception.

 We can define our own set of conditions or rules and throw an exception explicitly using

throw keyword.
 Syntax of throw keyword:

throw new exception_class("error message");


 For example:

throw new ArithmeticException("dividing a number by 5 is not allowed in this


program");
17
Java throw keyword example
 In this example, we have created the validate method that takes integer value as a parameter. If the age is less
than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote
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 Output:
code..."); Exception in thread main
} java.lang.ArithmeticException:not valid
18 }
User defined exception in java

 In java we have already defined, exception classes such as ArithmeticException,

NullPointerException etc.
 These exceptions are already set to trigger on pre-defined conditions such as when you

divide a number by zero it triggers ArithmeticException


 In java we can create our own exception class and throw that exception using throw

keyword
 These exceptions are known as user-defined or custom exceptions

19
Example of User defined exception in Java
/* This is my Exception class, I have named it MyException class Example1{
* you can give any name, just remember that it should public static void main(String args[]){
* extend Exception class try{
*/ System.out.println("Starting of try block");
class MyException extends Exception{ // I'm throwing the custom exception using throw
String str1; throw new MyException("This is My error
/* Constructor of custom exception class Message");
* here I am copying the message that we are passing while }
* throwing the exception to a string and then displaying catch(MyException exp){
* that string along with the message. System.out.println("Catch Block") ;
*/ System.out.println(exp) ;
MyException(String str2) { }
str1=str2; }
} }
public String toString(){
return ("MyException Occurred: "+str1) ; Output:
} Starting of try block
} Catch Block
MyException Occurred: This is My error Message
20
Thank
You!!

21

You might also like