Exception Handling
Difference between error and exception:
Errors indicate that something severe enough has gone wrong, the application
should crash rather than try to handle the error.
Exceptions are events that occurs in the code. A programmer can handle such
conditions and take necessary corrective actions.
Advantage of exception handling:
Exception handling ensures that the flow of the program doesn’t break when an exception occurs.
For example, if a program has bunch of statements and an exception occurs mid way after
executing certain statements then the statements after the exception will not execute and the
program will terminate abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.
class StackOverflow {
public static void test(int i)
{
if (i == 0)
return;
else {
test(i++);
}
}
}
public class ErrorEg {
public static void main(String[] args)
{
[Link](5);
}
}
Output:
Exception in thread "main" [Link]
at [Link]([Link])
at [Link]([Link])
at [Link]([Link])
at [Link]([Link])
at [Link]([Link])
...
Exception Handling in java
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.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs:
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run out of
memory.
Three categories of Exceptions:
Checked exceptions
Unchecked exceptions
Errors
import [Link];
• Checked exceptions − A checked
exception is an exception that is import [Link];
checked (notified) by the compiler at
compilation-time, these are also public class FilenotFound_Demo {
called as compile time exceptions.
These exceptions cannot simply be
ignored, the programmer should public static void main(String args[]) {
take care of (handle) these
exceptions. File file = new File("E://[Link]");
• E.g. IOException, SQLException etc. FileReader fr = new FileReader(file);
}
Output:
}
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be
thrown
FileReader fr = new FileReader(file);
^
1 error
• Unchecked exceptions − An public class Unchecked_Demo
unchecked exception is an {
exception that occurs at the
time of execution. These are public static void main(String
also called as Runtime args[]) {
Exceptions. These include
programming bugs, such as logic int num[] = {1, 2, 3, 4};
errors or improper use of an
API. Runtime exceptions are [Link](num[5]);
ignored at the time of }
compilation. }
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
Output
Exception in thread "main" [Link]: 5 at
Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
3. Errors − These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything about an
error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of
compilation. e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
A method catches an exception using a combination
Exception Hierarchy of the try and catch keywords. A try/catch block is
placed around the code that might generate an
exception. Code within a try/catch block is referred
to as protected code, and the syntax for using
try/catch looks like the following Catching
Exceptions:
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
Example#1:
Output:
// File Name : [Link] Exception thrown :
import [Link].*; [Link]: 3
Out of the block
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
[Link]("Access element three :" +
a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception thrown :" + e);
}
[Link]("Out of the block");
}
}
Example#2
public class JavaExceptionExample{
public static void main(String args[]){
try{
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
[Link]("rest of the code...");
}
}
Output:
[Link]: / by zero
rest of the code...
A finally block appears at the end of the catch blocks and has the following syntax −
public class ExcepTest {
public static void main(String args[]) {
int a[] = new int[2];
try {
[Link]("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Exception thrown :" + e);
}finally {
a[0] = 6;
[Link]("First element value: " + a[0]);
[Link]("The finally statement is executed");
}
}
Output:
} Exception thrown
:[Link]: 3
First element value: 6
The finally statement is executed
Here is code segment showing how to use multiple try/catch statements:
try {
file = new FileInputStream(fileName);
x = (byte) [Link]();
} catch (IOException i) {
[Link]();
return -1;
} catch (FileNotFoundException f) // Not valid! {
[Link]();
return -1;
}
Catching Multiple Type of Exceptions:
• Since Java 7, you can handle more than one exception using
a single catch block, this feature simplifies the code. Here is
how you would do it −
catch (IOException|FileNotFoundException ex) {
[Link](ex);
throw ex;
Differences between final, finally and finalize:
No. final finally finalize
1) Final is used to apply Finally is used to Finalize is used to
restrictions on class, method place important perform clean up
and variable. Final class can't code, it will be processing just
be inherited, final method can't executed whether before object is
be overridden and final exception is handled garbage collected.
variable value can't be or not.
changed.
2) Final is a keyword. Finally is a block. Finalize is a
method.
(i) (ii)
class FinalExample{ class FinallyExample{
public static void main(String[] args){ public static void main(String[] args){
try{
final int x=100; int x=300;
x=200; }catch(Exception e){[Link](e);}
}} finally{[Link]("finally block is
executed");}
}}
(iii)
class Bike{
final void run(){[Link]("running");} }
class Honda extends Bike{
void run(){[Link]("running safely with 100kmph");}
public static void main(String args[])
{ Honda honda= new Honda();
[Link]();
}
}
The throw keyword: (User-defined Custom Exception)
The throw statement allows you to create a custom exception.
The throw statement is used together with an exception type.
There are many exception types available in Java:
ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsExc
eption, SecurityException, etc:
Example
• Throw an exception if age is below 18 (print "Access denied"). If
age is 18 or older, print "Access granted":
Example:
public class Main { public static void main(String[] args) {
static void checkAge(int age) { checkAge(15); // Set age to 15 (which is
if (age < 18) { below 18...)
throw new ArithmeticException("Access }
denied - You must be at least 18 years }
old.");
} Output:
else { Exception in thread "main"
[Link]("Access granted - You [Link]: Access
are old enough!"); denied - You must be at least 18 years old.
} at [Link]([Link])
} at [Link]([Link])
// Driver Program
// A Class that represents use-defined
expception public static void main(String args[])
class MyException extends Exception {
{ try
public MyException(String s) {
{ // Throw an object of user defined exception
// Call constructor of parent throw new
Exception MyException("CustamizeException");
super(s); }
} catch (MyException ex)
} {
[Link]("Caught");
// A Class that uses above MyException
public class Main // Print the message from MyException object
{ [Link]([Link]());
}
}
}
Example: try {
// A Class that represents use-defined // Throw an object of
expception user defined exception
class MyException extends Exception throw new
{ MyException();
}
} catch (MyException ex)
// A Class that uses above MyException {
public class setText [Link]("Caught");
{
// Driver Program [Link]([Link]
public static void main(String args[]) age());
{ }
}
}
Wrapper Classes :
A Wrapper class is a class whose object wraps or contains primitive data types. When we
create an object to a wrapper class, it contains a field and in this field, we can store
primitive data types. In other words, we can wrap a primitive value into a wrapper class
object.
What is the need of Wrapper Classes ?
Primitive Data types and their Corresponding Wrapper class
Autoboxing: Automatic conversion of primitive types to the object of their
corresponding wrapper classes is known as autoboxing. For example – conversion of int
to Integer, long to Long, double to Double etc.
• // Java program to demonstrate • ArrayList<Integer> arrayList = new
Autoboxing ArrayList<Integer>();
• import [Link]; • // Autoboxing because ArrayList
• class Autoboxing stores only objects
• { • [Link](25);
• public static void main(String[] args)
• { • // printing the values from object
• char ch = 'a'; • [Link]([Link](0));
• }
• // Autoboxing- primitive to • }
Character object conversion
• Character a = ch;
Unboxing: It is just the reverse process of autoboxing. Automatically converting an
object of a wrapper class to its corresponding primitive type is known as unboxing. For
example – conversion of Integer to int, Long to long, Double to double, etc.
// Java program to demonstrate Unboxing ArrayList<Integer> arrayList =
import [Link]; new
ArrayList<Integer>();
[Link](24);
class Unboxing
// unboxing because get method
{ returns
public static void main(String[] args) //an Integer object
{ int num = [Link](0);
Character ch = 'a';
// printing the values from
// primitive data types
// unboxing - Character object to primitive conversion
[Link](num);
char a = ch; }
}
Strings: <Syntex: <String_Type> <string_variable> = "<sequence_of_string>";
• Strings in Java are Objects that are String str = “UPES";
backed internally by a char array. 0 1 2 3 4
Since arrays are immutable str U P E S \0
(cannot grow), Strings are
immutable as well. Whenever a
Address 0x23452 0x23453 0x23454 0x23455 0x23456
change to a String is made, an
entirely new String is created.
// Java code to illustrate String
import [Link].*;
import [Link].*;
class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String s = “UPES_Doon"; // create a string using “String literal”
// Prints the String.
[Link]("String s = " + s);
// Declare String using new operator
String s1 = new String(" UPES_Doon "); //create a string using “new keyword”
// Prints the String.
[Link]("String s1 = " + s1);
}
}
Example:
(2)
(1)
public class Main {
public class Main { public static void main(String[] args) {
public static void main(String[] args) { String txt = "Please locate where
String txt = 'locate' occurs!";
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
[Link]("The length of the txt [Link]([Link]("locate")
string is: " + [Link]()); );
} }
} }
String Concatenation:
public class Main { public class Main {
public static void main(String args[]) public static void main(String[] args) {
{ String firstName = “UPES ";
String firstName = “UPES"; String lastName = "Doon";
String lastName = "Doon";
[Link](firstName + " " [Link]([Link](l
+ lastName); astName));
} }
} }
Adding Numbers and Strings:
(1) (2)
public class Main { public class Main {
public static void main(String[] public static void main(String[]
args) { args) {
int x = 10; String x = "10";
int y = 20; String y = "20";
int z = x + y; String z = x + y;
[Link](z); [Link](z);
} }
} }
(1)
public class Main {
public static void main(String[]
args) {
String x = "10";
int y = 20;
String z = x + y;
[Link](z);
}
}
StringBuffer class:
• StringBuffer is a peer class of String that provides much of the
functionality of strings. String represents fixed-length, immutable
character sequences while StringBuffer represents growable and
writable character sequences.
• StringBuffer may have characters and substrings inserted in the
middle or appended to the end. It will automatically grow to make
room for such additions and often has more characters preallocated
than are actually needed, to allow room for growth.
• StringBuffer Constructors • StringBuffer(String str): It
• StringBuffer( ): It reserves room for accepts a String argument that
16 characters without reallocation. sets the initial contents of the
• StringBuffer s=new StringBuffer(); StringBuffer object and
reserves room for 16 more
• StringBuffer( int size):It accepts an characters without
integer argument that explicitly sets reallocation.
the size of the buffer.
StringBuffer s=new StringBuffer(“UPESDoon");
• StringBuffer s=new StringBuffer(20);
• length( ) and capacity( ): import [Link].*;
class GFG {
• The length of a StringBuffer can public static void main(String[] args)
be found by the length( ) {
method, while the total StringBuffer s = new
allocated capacity can be found
by the capacity( ) method. StringBuffer(“UPESDoon");
int p = [Link]();
int q = [Link]();
[Link]("Length of
string UPESDoon=" + p);
[Link]("Capacity of
string UPESDoon=" + q);
}
}
append( ): It is used to add text at the end of the existence text. Here are a
few of its forms:
• StringBuffer append(String str)
• StringBuffer append(int num)
import [Link].*;
class GFG {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer(“UPES");
[Link](“Doon");
[Link](s);
[Link](1);
[Link](s); }
}
insert( ): It is used to insert text at the specified index position. These are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
import [Link].*;
[Link](5, 41.35d);
class StrExamp5 { [Link](s);
public static void main(String[] args)
{ [Link](8, 41.35f);
StringBuffer s = new [Link](s);
StringBuffer("UPESHigherEducation");
char a_arr[] = { 'N', 'e', 'e', 'r', 'a', 'j' };
[Link](4, "for");
[Link](s); [Link](2, a_arr);
[Link](s);
[Link](0, 1); }
[Link](s); }
StringBuilder Class
The StringBuilder in Java represents a mutable sequence of
characters. Since the String Class in Java creates an immutable
sequence of characters, the StringBuilder class provides an
alternative to String Class, as it creates a mutable sequence of
characters.
The function of StringBuilder is very much similar to
the StringBuffer class, as both of them provide an alternative to String
Class by making a mutable sequence of characters.
Class Hierarchy:
[Link]
↳ [Link]
↳ Class StringBuilder
Syntax:
public final class StringBuilder
extends Object
implements Serializable, CharSequence
Constructors in Java StringBuilder:
• StringBuilder(): Constructs a string builder with no characters in it and an
initial capacity of 16 characters.
• StringBuilder(int capacity): Constructs a string builder with no characters in it
and an initial capacity specified by the capacity argument.
• StringBuilder(CharSequence seq): Constructs a string builder that contains
the same characters as the specified CharSequence.
• StringBuilder(String str): Constructs a string builder initialized to the contents
of the specified string. Refer: Example
StringTokenizer class:
A StringTokenizer object internally maintains a current position within the string to be
tokenized. Some operations advance this current position past the characters processed.
A token is returned by taking a substring of the string that was used to create the
StringTokenizer object.
Constructors: StringTokenizer(String str, String delim,
boolean flag):
StringTokenizer(String str) : The first two parameters have same meaning.
str is string to be tokenized. The flag serves following purpose.
Considers default delimiters like new
line, space, tab, carriage return and form If the flag is false, delimiter characters serve to
feed. separate tokens.
For example, if string is “Hello UPES“ and
StringTokenizer(String str, String delim) : delimiter is " ", then tokens are “Hello" and
“UPES".
delim is set of delimiters that are used to
tokenize the given string.
If the flag is true, delimiter characters are
considered to be tokens. For example, if string
is "hello UPES" and delimiter is " ", then tokens
are "hello", " " and “UPES".
• Example
StringJoiner:
• StringJoiner is a class in [Link] package which is used to
construct a sequence of characters(strings) separated by a
delimiter and optionally starting with a supplied prefix and
ending with a supplied suffix. Though this can also be with the
help of StringBuilder class to append delimiter after each
string, StringJoiner provides an easy way to do that without
much code to write.
Syntax:
• public StringJoiner(CharSequence delimiter)
Constructors :
• StringJoiner(CharSequence delimiter)
• StringJoiner(CharSequence delimiter,CharSequence prefix,CharSequence suffix)
Methods : There are 5 methods in StringJoiner class.
1. String toString()
2. StringJoiner add(CharSequence newElement)
3. StringJoiner merge(StringJoiner other)
4. int length()
5. StringJoiner setEmptyValue(CharSequence emptyValue)
Example of showing methods
ClassLoader in Java:
• The Java ClassLoader is a part of the Java Runtime Environment
that dynamically loads Java classes into the Java Virtual
Machine. The Java run time system does not need to know
about files and file systems because of classloaders.
• Java classes aren’t loaded into memory all at once, but when
required by an application. At this point, the Java ClassLoader
is called by the JRE and these ClassLoaders load classes into
memory dynamically.
ClassLoader in Java: Continue..
Not all classes are loaded by a single ClassLoader. Depending on
the type of class and the path of class, the ClassLoader that loads
that particular class is decided.
A Java Classloader is of three types:
1. BootStrap ClassLoader
2. Extension ClassLoader
3. System ClassLoader