UNIT 4 -EXCEPTION HANDLING
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException ,
IOException , SQLException , RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:
1. statement 1;
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;
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
Hierarchy of Java Exception classes:
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception:The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception:The classes that inherit the RuntimeException are known as unchecked
exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time,
but they are checked at runtime.
3) Error:Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java Exception Keywords
Java provides five keywords that are used to handle the exception. The following table
describes each.
Keyword Description
The "try" keyword is used to specify a
block where we should place an exception
try code. It means we can't use try block
alone. The try block must be followed by
either catch or finally.
The "catch" block is used to handle the
exception. It must be preceded by try
catch block which means we can't use catch
block alone. It can be followed by finally
block later.
The "finally" block is used to execute the
necessary code of the program. It is
finally
executed whether an exception is handled
or not.
The "throw" keyword is used to throw an
throw
exception.
The "throws" keyword is used to declare
exceptions. It specifies that there may
throws occur an exception in the method. It
doesn't throw an exception. It is always
used with method signature.
Java Exception Handling Example
Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.
JavaExceptionExample.java
1. public class JavaExceptionExample{
2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
Difference Between Exception and Error:
In Java, Error, and Exception both are subclasses of the Java Throwable class that belongs to
java.lang package.
Basis of Exception Error
Comparison
Recoverable/
Exception can be recovered by using the try-
Irrecoverabl
catch block. An error cannot be recovered.
e
It can be classified into two categories i.e. All errors in Java are
Type
checked and unchecked. unchecked.
Occurrence It occurs at compile time or run time. It occurs at run time.
It belongs to java.lang.Error
Package It belongs to java.lang.Exception package.
package.
Known or Only checked exceptions are known to the Errors will not be known to
unknown compiler. the compiler.
It is mostly caused by the
Causes It is mainly caused by the application itself. environment in which the
application is running.
Checked Exceptions: SQLException,
IOException Java.lang.StackOverFlow,
Example Unchecked java.lang.OutOfMemoryErr
Exceptions: ArrayIndexOutOfBoundExceptio or
n, NullPointerException, ArithmaticException
try-catch block:
Java try 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 in the try block, the rest of the block code will not
execute. So, it is recommended not to keep the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
Syntax of try-finally block
1. try{
2. //code that may throw an exception
3. }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.
Advertisement
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
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM
provides a default exception handler that performs the above following tasks.
Example:
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
Output: Something went wrong.
The 'try catch' is finished.
Java finally block
Java finally block is a block used to execute important code such as closing the connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it contains all
the necessary statements that need to be printed regardless of the exception occurs or not.
The finally block follows the try-catch block.
Use finally keyword
o finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
o The important statements to be printed can be placed in the finally block.
1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. System.out.println(data);
6. }
7. catch(NullPointerException e){
8. System.out.println(e);
9. }
10. finally {
11. System.out.println("finally block is always executed");
12. }
13. System.out.println("rest of phe code...");
14. }
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 the normal flow of the program 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
checking the code before it being used.
Syntax of Java throws
1. return_type method_name() throws exception_class_name{
2. //method code
3. }
Which exception should be declared?
Ans: Checked exception only, because:
o unchecked exception: under our control so we can correct our code.
o error: beyond our control. For example, we are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
Advertisement
It provides information to the caller of the method about the exception.
Java throws Example
Let's see the example of Java throws clause which describes that checked exceptions can be
propagated by throws keyword.
Testthrows1.java
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Difference between throw and throws in Java
The throw and throws is the concept of exception handling where the throw keyword throw
the exception explicitly from a method or a block of code whereas the throws keyword is
used in signature of the method.
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
Sr. no. Basis of throw throws
Differences
Java throws
Java throw keyword is
keyword is used in the
used throw method
an signature to
exception declare an
1. Definition explicitly in exception
the code, which might
inside the be thrown by
function or the function
the block of while the
code. execution of
the code.
Type of Using throws
exception keyword, we
Using throw can declare
keyword, both checked
we can only and
propagate unchecked
unchecked exceptions.
2. Usage exception However, the
i.e., the throws
checked keyword can
exception be used to
cannot be propagate
propagated checked
using throw exceptions
only. only.
The throw
keyword is The throws
followed by keyword is
an instance followed by
3. Syntax
of class names
Exception of Exceptions
to be to be thrown.
thrown.
throw is throws is
used within used with the
4. Declaration
the method
method. signature.
We can
declare
We are
multiple
allowed to
exceptions
throw only
using throws
one
keyword that
Internal exception at
5. can be
implementation a time i.e.
thrown by the
we cannot
method. For
throw
example,
multiple
main() throws
exceptions.
IOException,
SQLException.
Array and String: Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.
array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects
in an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in
Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows
automatically.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java
1. dataType[] arr; (or)
2. dataType []arr; (or)
3. dataType arr[];
Instantiation of an Array in Java
1. arrayRefVar=new datatype[size];
Example of Java Array
1. //Java Program to illustrate how to declare, instantiate, initialize
2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don't need to declare the array
while passing an array to the method.
1. //Java Program to demonstrate the way of passing an anonymous array
2. //to method.
3. public class TestAnonymousArray{
4. //creating a method which receives an array as a parameter
5. static void printArray(int arr[]){
6. for(int i=0;i<arr.length;i++)
7. System.out.println(arr[i]);
8. }
9. public static void main(String args[]){
10. printArray(new int[]{10,22,44,66});//passing anonymous array to method
11. }}
Java String:
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
No. Method Description
It returns char value for the
1 char charAt(int index)
particular index
2 int length() It returns string length
static String format(String format,
3 It returns a formatted string.
Object... args)
static String format(Locale l, String It returns formatted string with
4
format, Object... args) given locale.
It returns substring for given begin
5 String substring(int beginIndex)
index.
String substring(int beginIndex, int It returns substring for given begin
6
endIndex) index and end index.
It returns true or false after
7 boolean contains(CharSequence s) matching the sequence of char
value.
static String join(CharSequence
8 delimiter, CharSequence... It returns a joined string.
elements)
static String join(CharSequence
9 delimiter, Iterable<? extends It returns a joined string.
CharSequence> elements)
It checks the equality of string
10 boolean equals(Object another)
with the given object.
11 boolean isEmpty() It checks if string is empty.
It concatenates the specified
12 String concat(String str)
string.
It replaces all occurrences of the
13 String replace(char old, char new)
specified char value.
String replace(CharSequence old, It replaces all occurrences of the
14
CharSequence new) specified CharSequence.
static String It compares another string. It
15
equalsIgnoreCase(String another) doesn't check case.
It returns a split string matching
16 String[] split(String regex)
regex.
It returns a split string matching
17 String[] split(String regex, int limit)
regex and limit.
18 String intern() It returns an interned string.
It returns the specified char value
19 int indexOf(int ch)
index.
It returns the specified char value
20 int indexOf(int ch, int fromIndex)
index starting with given index.
It returns the specified substring
21 int indexOf(String substring)
index.
int indexOf(String substring, int It returns the specified substring
22
fromIndex) index starting with given index.
23 String toLowerCase() It returns a string in lowercase.
It returns a string in lowercase
24 String toLowerCase(Locale l)
using specified locale.
25 String toUpperCase() It returns a string in uppercase.
It returns a string in uppercase
26 String toUpperCase(Locale l)
using specified locale.
It removes beginning and ending
27 String trim()
spaces of this string.
It converts given type into string.
28 static String valueOf(int value)
It is an overloaded method.
The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java
by using these three classes.
The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder
classes.
ava String class methods
The java.lang.String class provides many useful methods to perform operations on sequence of
char values.
Mutable Immutable
Once an immutable object is
We can change the value of mutable
initiated; We can not change its
objects after initialization.
values.
The state can be changed. The state can not be changed.
In immutable objects, a new object is
In mutable objects, no new objects
formed when the value of the object
are formed.
is altered.
It provides methods to change the It does not provide any method to
object. change the object value.
It supports get() and set() methods to It only supports get() method to pass
dela with the object. the value of the object.
Mutable classes are may or may not
Immutable classes are thread-safe.
be thread-safe.
The essentials for creating a mutable The essentials for creating an
class are methods for modifying immutable class are final class,
fields, getters and setters. private fields, final mutable objects.
Why are Strings in Java Immutable
String in Java is a very special class, as it is used almost in every Java program. That's why it is
Immutable to enhance performance and security. Let's understand it in detail:
In Java, strings use the concept of literals. Suppose we have an object having many reference
variables. In such a scenario, if we will change the value of a reference variable, it will affect the
entire object and all of its values.
Apart from the above reasons, the following reasons are also responsible for making the String
immutable:
String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.
1) StringBuffer Class append() Method
The append() method concatenates the given argument with this String.
StringBufferExample.java
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
2) StringBuffer insert() Method
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java
1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }