Exception Handling-Converted1
Exception Handling-Converted1
What is Exception?
An exception (or exceptional event) is a problem/ error that arises during the
execution of a program. When an Exception occurs the normal flow of the
program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
1. Checked Exception
2. Unchecked Exception
3. Error
For example, if you use FileReader class in your program to read data
from a file, if the file specified in its constructor doesn't exist, then
a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
importjava.io.File;
importjava.io.FileReader;
publicclassFilenotFound_Demo{
publicstaticvoid main(Stringargs[]){
Filefile=newFile("E://file.txt");
FileReaderfr=newFileReader(file);
}
}
If you try to compile the above program, you will get the following
exceptions.
Output:
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReaderfr = new FileReader(file);
^
1 error
Example
PublicclassUnchecked_Demo
{
publicstaticvoid main(Stringargs[])
{
intnum[]={1,2,3,4};
System.out.println(num[5]);
}
}
If you compile and execute the above program, you will get the following
exception.
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
atExceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
3) Error: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, stack
overflow, OutOfMemoryError,etc. They are also ignored at the time of
compilation.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The
exception class is a subclass of the Throwable class. Other than the exception
class there is another subclass called Error which is derived from the
Throwable class.
statement 1;
statement 2;
statement 3;//exception occurs
statement 4;
statement 5;
statement 6;
Suppose there are 6 statements in our program and there occurs an exception
at statement 3, the rest of the code will not be executed i.e. statement 4 to 6
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.
Java provides five keywords that are used to handle the exception. The
following table describes each.
Keyword Description
Syntax:
try
{
// code that may raise exception
}
catch (ExceptionName e1)
{
// Catch block
}
//rest code of the program
Let's see an example of Java Exception Handling in which we are using a try-
catch statement to handle the exception.
JavaExceptionExample.java
Catching Exceptions
A method catches an exception using a combination 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 –
Syntax
Try
{
// Protected code
} catch (ExceptionName e1)
{
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an
exception occurs, that exception occurred is handled by catch block associated
with it. Every try block should be immediately followed either by a catch block
or finally block.
A catch statement involves declaring the type of exception you are trying to
catch. If an exception occurs in protected code, the catch block or blocks that
follows the try is checked. If the type of exception that occurred is listed in a
catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.
Example:
class Excep
{
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
}
The previous statements demonstrate three catch blocks, but you can have any
number of them after a single try. If an exception occurs in the protected code,
the exception is thrown to the first catch block in the list. If the data type of the
exception thrown matches ExceptionType1, it gets caught there. If not, the
exception passes down to the second catch statement. This continues until the
exception either is caught or falls through all catches, in which case the
current method stops execution and the exception is thrown down to the
previous method on the call stack.
Example 1:
Here is code segment showing how to use multiple try/catch statements.
// Demonstrate multiple catch statements.
import java.util.*;
class Multi_Exec {
public static void main(String args[]) {
Scanner s=new Scanner(System.in);
try {
System.out.println("Enter Value");
int a = s.nextInt();
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Example 2:
// A Java program to demonstrate that we needed multiple catch blocks for
// multiple exceptions
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
try
{
System.out.println(“Enter a value ");
int n = scn.nextInt();
if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
}
}
Output 1:
Enter a value
Madhu
Exception encountered java.lang.NumberFormatException:
For input string: "Madhu"
Output 2:
Enter a value
0
Arithmetic Exception encountered java.lang.ArithmeticException: / by zero
throw Keyword:
The Java throw keyword is used to throw an exception explicitly.
Example
Output:
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)
throws Keyword:
If a method does not handle a checked exception, the method must declare it
using the throws keyword. The throws keyword appears at the end of a
method's signature.
A throws clause lists the types of exceptions that a method might throw. This is
necessary for all exceptions, except those of type Error or RuntimeException, or
any of their subclasses.
All other exceptions that a method can throw must be declared in the throws
clause. If they are not, a compile-time error will result.
This is the general form of a method declaration that includes a throws clause:
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
Output:
Inside check function
caughtjava.lang.ArithmeticException: demo
Difference between throw and throws
throw throws
Finally Block:
The finally block follows a try block or a last catch block.
The finally block in java is used to put important codes such as clean up
code e.g. closing the file or closing the connection.
The finally block executes whether exception rise or not and whether
exception handled or not.
class GFG {
public static void main(String[] args)
{
try {
System.out.println("inside try block");
System.out.println("Arithmetic Exception");
}
// Always execute
finally {
System.out.println(
"finally : i execute always.");
}
}
}
Output
inside try block
17
finally : i execute always.
Case 2: When the exception rises and handled by the catch block
In this case, the program throws an exception but handled by the catch block,
and finally block executes after the catch block.
import java.io.*;
class GFG {
System.out.println(
"catch : exception handled.");
}
// Always execute
finally {
Case 3: When exception rise and not handled by the catch block
In this case, the program throws an exception but not handled by catch so
finally block execute after the try block and after the execution of finally block
program terminate abnormally, But finally block execute fine.
import java.io.*;
class GFG {
public static void main(String[] args)
{
try {
System.out.println("Inside try block");
System.out.println(
"catch : exception not handled.");
}
// Always execute
finally {
System.out.println(
"finally : i will execute always.");
}
// This will not execute
System.out.println("i want to run");
}
}
Output
Inside try block
finally : i will execute always.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)
Note the following −
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses whenever a try/catch block is
present.
The try block cannot be present without either catch clause or finally
clause.
Any code cannot be present in between the try, catch, finally blocks.
User-defined/custom Exceptions:
Java provides us the facility to create our own exceptions which are basically
derived classes of Exception.
Creating our own Exception is known as a custom exception or user-defined
exception.
Basically, Java custom exceptions are used to customize the exception
according to user needs.
In simple words, we can say that a User-Defined Exception or custom
exception is creating your own exception class and throwing that exception
using the ‘throw’ keyword.
You just need to extend the predefined Exception class to create your own
Exception. These are considered to be checked exceptions.
Example:
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (MyException ex)
{
System.out.println("Caught the exception");
Output:
F:\java>java MyException
Method Description
hasNext() It returns true if the iterator has more elements
otherwise it returns false.
next() It returns the element and moves the cursor
pointer to the next element.
remove() It removes the last elements returned by the
iterator. It is less used.
There are many methods declared in the Collection interface. They are as follows:
Method Description
ArrayList
LinkedList
Vector
Stack
Methods of List:
The List interface includes all the methods of the Collection interface. Its because
Collection is a super interface of List.
Some of the commonly used methods of the Collection interface that's also
available in the List interface are:
Arraylist:
Java ArrayList class uses a dynamic array for storing the elements.
It is like an array, but there is no size limit.
We can add or remove elements anytime. So, it is much more flexible than
the traditional array.
It is found in the java.util package. It is like the Vector in C++.
Creating an ArrayList
Before using ArrayList, we need to import the java.util.ArrayList package first.
Here is how we can create arraylists in Java:
ArrayList<Type> arrayList= new ArrayList<>();
For example,
In the above program, we have used Integer not int. It is because we cannot use
primitive types while creating an arraylist. Instead, we have to use the
corresponding wrapper classes.
import java.util.*;
class ArrayListExample
{
public static void main(String args[])
{
Linked List:
Linked List is a sequence of links which contains items. Each link contains a
connection to another link.
Java Linked List class uses two types of Linked list to store the elements:
Doubly Linked List: In a doubly Linked list, it has two references, one to the
next node and another to previous node. You can refer to the below image to get
a better understanding of doubly linked list.
Some of the methods in the linked list are listed below:
Method Description
It is used to append the specified element to the end
boolean add( Object o)
of the list.
boolean Returns true if this list contains the specified
contains(Object o) element.
void add (int index, Inserts the element at the specified element in the
Object element) list.
It is used to insert the given element at the
void addFirst(Object o)
beginning.
void addLast(Object o) It is used to append the given element to the end.
int size() It is used to return the number of elements in a list
boolean remove(Object Removes the first occurrence of the specified element
o) from this list.
int indexOf(Object Returns the index of the first occurrence of the
element) specified element in this list, or -1.
int lastIndexOf(Object Returns the index of the last occurrence of the
element) specified element in this list, or -1.
Vector:
Vector uses a dynamic array to store the data elements. It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the part of
Collection framework.
Creating a Vector
Here is how we can create vectors in Java.
Methods of Vector
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Using remove()
String element = animals.remove(1);
System.out.println("Removed Element: " + element);
System.out.println("New Vector: " + animals);
// Using clear()
animals.clear();
System.out.println("Vector after clear(): " + animals);
}
}
Output:
Initial Vector: [Dog, Horse, Cat]
Removed Element: Horse
New Vector: [Dog, Cat]
Vector after clear(): []
Stack:
The stack is a linear data structure that is used to store the collection of objects.
It is based on Last-In-First-Out (LIFO). Java collection framework provides many
interfaces and classes to store the collection of objects. One of them is the Stack
class that provides different operations such as push, pop, search, etc.
The stack data structure has the two most important operations that are push
and pop. The push operation inserts an element into the stack and pop
operation removes an element from the top of the stack. Let's see how they work
on stack.
Creating a Stack
If we want to create a stack, first, import the java.util package and create an
object of the Stack class.
Example:
import java.util.Stack;
public class StackExample
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
System.out.println("poped Element in Stack: " + stk.pop());
result = stk.empty();
System.out.println("Is the stack empty? " + result);
}
}
Output:
Is the stack empty? true
Elements in Stack: [78, 113, 90, 120]
poped Element in Stack:120
Is the stack empty? False
Introduction to JavaBeans:
JavaBeans are classes that encapsulate many objects into a single object (the
bean). It is a java class that should follow following conventions:
Methods: JavaBeans can have methods beyond the standard getter and
setter methods. These methods enable the component to perform various
actions and operations.
Example:
Output:
BCA