Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

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.
Exception Handling

• Run Time errors occurs during execution of program.


• Java compiler will not detect Run Time errors.
• Only Java Virtual Machine (JVM) will detect it while executing the
program.

Example:

class RunTimeErrorDemo {
public static void main(String args[]) {
int arr[] = new int[4];
arr[5] = 100;
System.out.println("Success");
}}
Compile Time Error:
Errors that occur during compiling the program
and if there any syntax error in the program
like missing semicolon at the end of a
statement or curly braces etc., then the Java
compiler displays the error on to the screen.
Example:
class CompileTimeDemo {
public static void main(String as[])
int i=10; j=20;
System.out.println(i)
} }
Logical Error:
In Java logical error is nothing but when a program is
compiled and executed without any error but not producing
any result is called as logical error.
These errors can’t be detected by neither compiler nor JVM.
This errors occur due to poor logic written by the programmer.

Java - Exceptions
An exception (or exceptional event) is a problem 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.
Reasons for Exceptions to occur

• 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

• Some of these exceptions are caused by user error,


others by programmer error, and others by physical
resources that have failed in some manner
What happens when an exception is occurred and not handled.

• Whenever JVM encounters a runtime error, it creates an


object of the corresponding exception class and since this
object is not explicitly handled, this object reaches back to
the JVM. The JVM accepts these objects and terminates
the program.
• When we do not handle the exception, then it is abnormal
termination.
• Every exception is a predefined class in java. The
predefined classes are part of java.lang package and
whose objects are created by JVM whenever it encounters
a runtime error.
• For each and every runtime error, there is a
corresponding exception class in the java.lang package.
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.
Types of Exceptions
• Types of Exceptions
• Exceptions are classified into two types
• 1) Error
• 2) Exception

Error class:
Exceptions of type Error are related to errors that occur in the java
virtual machine itself, and not in our program.
These types of exceptions are beyond our control, and our program
will not handle them. Normally programs cannot recover from
error. Example: OutOfMemoryError and UnknownError.

Exception Class:
Here the programs can handle the exceptions that occur at the time
of compiling and running the program.
Two types of subclasses
1) RuntimeExceptions or Unchecked Exceptions
Unchecked Exceptions or Runtime Exceptions
• The unchecked exceptions are those exceptions that occur
during the execution of the program. Hence they are also
referred to as Runtime exceptions.
• These exceptions are generally ignored during the compilation
process. They are not checked while compiling the program.
• The exception objects for which compiler does not compel to
handle them is known as unchecked exceptions.

Checked Exceptions
• Checked exceptions are also known as compile-time exceptions
as these exceptions are checked by the compiler during the
compilation process to confirm whether the exception is
handled by the programmer or not. If not, then the system
displays a compilation error.
• The Exception objects for which compiler compels to handle
then is known as checked exceptions.
Popular examples of Checked Exceptions:
IOException: While using file input/output stream related
exception
SQLException : While executing queries on database
related to SQL syntax
DataAccessException :Exception related to accessing
data/database
ClassNotFoundException : Thrown when the JVM
can’t find a class it needs, because of a command-line error, a
classpath issue, or a missing .class file
InstantiationException: Attempt to create an object of
an abstract class or interface.
InterruptedException : one tread has been interrupted
by another thread.
NoSuchFieldException : a requested field does not exist
Popular Unchecked Exceptions:
NullPointerException : Thrown when attempting to access
an object with a reference variable whose current value is null
ArrayIndexOutOfBound : Thrown when attempting to
access an array with an invalid index value (either negative or
beyond the length of the array)
IllegalArgumentException : Thrown when a method
receives an argument formatted differently than the method
expects.
IllegalStateException: Thrown when the state of the
environment doesn’t match the operation being attempted,e.g.,
using a Scanner that’s been closed.
NumberFormatException : Thrown when a method that
converts a String to a number receives a String that it cannot
convert.
ArithmaticException: Arithmetic error, such as divide-by-
zero.
Exception Handling in java

• Exceptions can be handled by using try catch block.


• To catch and handle an exception, we place the try...catch
block around the code that might generate an exception.
• Here's the syntax of try...catch block:
try {
// code
}
catch(Exception e) {
// code
}
• Here, the code that might generate an exception is placed in
the try block. Every try block is followed by a catch block.
• When an exception occurs, it is caught by the catch block. The
catch block cannot be used without the try block.,
Example: Exception handling using try...catch

class Main {
public static void main(String[] args) {
try {
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " +
e.getMessage());
}}}

Output
ArithmeticException => / by zero
• In the example, we are trying to divide a number by 0.
Here, this code generates an exception.
• To handle the exception, we have put the code, 5 / 0
inside the try block. Now when an exception occurs, the
rest of the code inside the try block is skipped.
• The catch block catches the exception and statements
inside the catch block is executed.
• If none of the statements in the try block generates an
exception, the catch block is skipped.
• If an error occurs in the try block, then JVM creates an
object of corresponding exception class and throws it .
The catch block will receive the reference and handles
appropriately.
Multiple Catch Block
• In Java, a single try block can have multiple catch
blocks.
• When statements in a single try block generate
multiple exceptions, we require multiple catch
blocks to handle different types of exceptions.
• This mechanism is called multi-catch block in java.
• Each catch block is capable of catching a different
exception.
• That is each catch block must contain a different
exception handler.
try
{
statements;
}
catch(ExceptionType1 e1)
{
statements;
}
catch(ExceptionType2 e2)
{
statements;
}
catch(ExceptionType3 e3)
{
statements;
}
...
catch(ExceptionTypen en)
{
statements;
}
Output is -:
Exception Caught -
java.langArrayIndexOutOfBoundsException: 5
• Java multi-catch block acts as a case in a switch statement.
In the above syntax, if the exception object
(ExceptionType1) is thrown by try block, the first catch
block will catch the exception object thrown and the
remaining catch block will be skipped.
• In case, exception object thrown does not match with the
first catch block, the second catch block will check and so
on.
• At a time only one exception occurs and at a time only one
catch block is used
• In this code, we have three catch blocks associated with one try
block. At the runtime, code in try block throws an exception of
type ArrayIndexOutOfBoundsException, this exception type is
matched with the declared exception type in every catch-
block(matching starts with the first catch block).
• The catch block that matches with type of exception thrown is
executed, while the rest of catch blocks are skipped. Let's see how
-
• •••The first catch block declared an exception of type
ArrayStoreException, which doesn't match with the exception
ArrayIndexOutOfBoundsException thrown by the try block,
hence this catch-block is not executed.
• •••ArrayIndexOutOfBoundsException declared in the second
catch block matches with the exception
ArrayIndexOutOfBoundsException thrown by the try block and
hence second catch block will be executed.
•••As, we have already found the matching catch block, hence,
the third catch block with declared exception of type Exception is
skipped and not executed, even though Exception is superclass of
ArrayIndexOutOfBoundsException class.

Placement of a catch block is very important


The catch-block declared with a specific exception class must
always be placed above the catch-block declared with a less
specific/general superclass exception class, otherwise, Java
Compiler will throw a compile-time error.
••• For eg:in the above example, if we would placed third catch
which is containing Exception class in the place of first catch, then
it would have matched with first catch only.
Even though specific reference of the exception is mentioned in
sec catch block(arrayindeoutofbounds).
This is because Exception is the superclass for
Arrayindeoutofbounds exception.
finally block
It 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
Syntax of Finally block
try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
A Simple Example of finally block
Here you can see that the exception occurred in try block which has been
handled in catch block, after that finally block got executed.
class Example
{ Output:
public static void main(String args[]) { Number should not be divided by
try{ zero
int num=121/0; This is finally block
System.out.println(num); Out of try-catch-finally
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block */
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
} }
Few Important points regarding finally block
1. 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.
2. Finally block is optional, as we have seen in previous
tutorials 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.
3. 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.
4. The statements present in the finally block execute even if
the try block contains control transfer statements like return,
break or continue.
5) if an exception occurred within try block and none of the catch
blocks could handle it, still the finally clause is executed after
abrupt termination of try, so, the bottom line is that the code in a
finally clause is almost certainly executed.

The throw Statement:


The throw keyword is used to explicitly throw a single exception.
When an exception is thrown, the flow of program execution
transfers from the try block to the catch block. We use the throw
keyword within a method.

Syntax: throw Instance


Example: throw new ArithmeticException("/ by zero");
The flow of execution of the program stops immediately after
the throw statement is executed and the nearest enclosing try
block is checked to see if it has a catch statement that matches
the type of exception. If it finds a match, controller is transferred
to that statement otherwise next enclosing try block is checked
and so on.
Eg: public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("You are Eligible to Vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}}
The throws keyword

throws is a keyword in Java which is used in the signature


of method to indicate that this method might throw one of
the listed type exceptions. The caller to these methods has
to handle the exception using a try-catch block.

Syntax : type method_name(parameters) throws


exception_list

//exception_list is a comma separated list of all the


//exceptions which a method might throw.
Example 1: Java throws Keyword
import java.io.*;
class Main {
public static void findFile() throws IOException {
// code that may produce IOException
File newFile=new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e){
System.out.println(Output) ; } } }

O/P : java.io.FileNotFoundException: test.txt (No such file or


directory)
When we run this program, if the file test.txt does not exist,
FileInputStream throws a FileNotFoundException which extends
the IOException class.

If a method does not handle exceptions, the type of exceptions


that may occur within it must be specified in the throws clause
so that methods further up in the call stack can handle them or
specify them using throws keyword themselves.

The findFile() method specifies that an IOException can be


thrown. The main() method calls this method and handles the
exception if it is thrown by using try catch block.
User Defined Exceptions
class MyFirstException extends Exception {
public UDException(String s)
{
// Call constructor of parent Exception
super(s);
} }

public class MainClass {


public static void main(String args[])
{
try {
// Throw an object of user defined exception
throw new UDException("It is an User Defined Exception ");
}
catch (UDException ex) {
System.out.println("Caught the Exception");

// Print the message from UDException object


System.out.println(ex.getMessage());
} } }
Example: NegativeageException Exception
Idenitify the errors/
output
Exercise-1

class ArrayIndexOutOfBound_Demo {
    public static void main(String args[])
    {
        try{
            int a[] = new int[5];
            a[6] = 9;         }
        catch(ArrayIndexOutOfBoundsException e) {
    System.out.println ("Array Index is Out Of Bounds");
        }    } }
Exercise-2

class  NumberFormat_Demo
{
    public static void main(String args[])
    {
        try {
            int num = Integer.parseInt ("akki") ;
            System.out.println(num);
        } catch(NumberFormatException e) {
     System.out.println("Number format exception");
        }     } }
class Test{
Exercise-3
    public static void main(String[] args)    {
        try
        {
            int a[]= {1, 2, 3, 4};
            for (int i = 1; i <= 4; i++)
            {
                System.out.println ("a[" + i + "]=" + a[i] + "n");
            }
        }      
        catch (Exception e)
        {
            System.out.println ("error = " + e);
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
          System.out.println ("ArrayIndexOutOfBoundsException");
        }    }
}
Exercise-4
class Test{
    public static void main (String[] args)    {
        try
        {
            int a = 0;
            System.out.println ("a = " + a);
            int b = 20 / a;
            System.out.println ("b = " + b);
        }
         catch(ArithmeticException e)
        {
            System.out.println ("Divide by zero error");
        }
 
        finally
        {
            System.out.println ("inside the finally block");
        }     } }

You might also like