Exception Handling in Java: Basics, Examples, and Importance

undefined
Dr.Umayal Ramanathan College for Women
Affiliated to Alagappa University, Karaikud
i
 
Accredited with B+ Grade by NAAC
Department of Information TechnologY
Java programming
7BIT2C1
Unit IV- Exception Handling
Dr.L.Visalatchi
Associate Professor
Department of IT
Department of INformation Technology,URCW
What is an Exception?
Difference between error and exception?
How to do Exception handling? - Keywords
Important Exceptions.
Exception Hierarchy
Example program
Exception Handling
Department of INformation Technology,URCW
Exception is an abnormal condition.
In Java, an exception is an event that disrupts the
normal flow of the program.
When an exception occurs program execution gets
terminated. In such cases we get a system generated
error message.
What is an Exception in java?
Department of INformation Technology,URCW
There can be several reasons that can cause a
program to throw exception. For example: Opening a
non-existing file in your program, Network
connection problem, bad input data provided by user
etc.
Why an exception occurs?
Department of INformation Technology,URCW
 
Exception Handling is a mechanism to handle runtime
errors such as ClassNotFoundException, IOException,
SQLException, RemoteException, etc. It is handled as an
object which is thrown at runtime.
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.
Why do we handle Exception
Department of INformation Technology,URCW
Error:
 
Error is irrecoverable. Some example of errors are
OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Exception:
 
Exceptions are recoverable and could be handled.
Difference between Error and
Exception
Department of INformation Technology,URCW
try:
 
 
The "try" keyword is used to specify a block where we should  
 
place an
exception code. It means we can't use try block alone. 
 
The try block must be followed by
either catch or finally.
c
a
t
c
h
:
 
T
h
e
 
"
c
a
t
c
h
"
 
b
l
o
c
k
 
i
s
 
u
s
e
d
 
t
o
 
h
a
n
d
l
e
 
t
h
e
 
e
x
c
e
p
t
i
o
n
.
 
I
t
 
m
u
s
t
 
b
e
 
p
r
e
c
e
d
e
d
b
y
 
t
r
y
 
b
l
o
c
k
 
w
h
i
c
h
 
m
e
a
n
s
 
w
e
 
c
a
n
'
t
 
u
s
e
 
c
a
t
c
h
 
b
l
o
c
k
 
a
l
o
n
e
.
 
I
t
 
c
a
n
 
b
e
 
f
o
l
l
o
w
e
d
 
b
y
 
f
i
n
a
l
l
y
b
l
o
c
k
 
l
a
t
e
r
.
f
i
n
a
l
l
y
:
 
T
h
e
 
"
f
i
n
a
l
l
y
"
 
b
l
o
c
k
 
i
s
 
u
s
e
d
 
t
o
 
e
x
e
c
u
t
e
 
t
h
e
 
n
e
c
e
s
s
a
r
y
 
c
o
d
e
 
o
f
 
t
h
e
p
r
o
g
r
a
m
.
 
I
t
 
i
s
 
e
x
e
c
u
t
e
d
 
w
h
e
t
h
e
r
 
a
n
 
e
x
c
e
p
t
i
o
n
 
i
s
 
h
a
n
d
l
e
d
 
o
r
 
n
o
t
.
t
h
r
o
w
:
 
T
h
e
 
"
t
h
r
o
w
"
 
k
e
y
w
o
r
d
 
i
s
 
u
s
e
d
 
t
o
 
t
h
r
o
w
 
a
n
 
e
x
c
e
p
t
i
o
n
.
t
h
r
o
w
s
:
 
T
h
e
 
"
t
h
r
o
w
s
"
 
k
e
y
w
o
r
d
 
i
s
 
u
s
e
d
 
t
o
 
d
e
c
l
a
r
e
 
e
x
c
e
p
t
i
o
n
s
.
 
I
t
 
s
p
e
c
i
f
i
e
s
 
t
h
a
t
 
t
h
e
r
e
m
a
y
 
o
c
c
u
r
 
a
n
 
e
x
c
e
p
t
i
o
n
 
i
n
 
t
h
e
 
m
e
t
h
o
d
.
 
I
t
 
d
o
e
s
n
'
t
 
t
h
r
o
w
 
a
n
 
e
x
c
e
p
t
i
o
n
.
 
I
t
 
i
s
 
a
l
w
a
y
s
 
u
s
e
d
w
i
t
h
 
m
e
t
h
o
d
 
 
s
i
g
n
a
t
u
r
e
.
Keywords in handling Exception
Department of INformation Technology,URCW
Syntax of try catch in java
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))‏
{
 //error handling code
 }
Steps in Exception handling
Department of INformation Technology,URCW
public
 
class
 JavaExceptionExample{
  
public
 
static
 
void
 main(String args[])
{
   
try
{
      //code that may raise exception
      
int
 data=100/0;
   }
catch
(ArithmeticException e)
{
System.out.println(e);
}
   //rest code of the program
   System.out.println("rest of the code...");
  }
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code...
 
Department of INformation Technology,URCW
A single try block can have any number of catch
blocks.
 A generic catch block can handle all the exceptions.
ArrayIndexOutOfBoundsException
ArithmeticException ,NullPointerException or any
other type of exception, this handles all of them.
Multiple catch blocks in Java
Department of INformation Technology,URCW
Flow chart for multiple catch
Department of INformation Technology,URCW
undefined
class Example2{
   public static void main(String args[]){
     try{
         int a[]=new int[7];
         a[4]=30/0;
         System.out.println("First print statement in try block");
     }
     catch(ArithmeticException e){
        System.out.println("Warning:ArithmeticException");
     }
     catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Warning:ArrayIndexOutOfBoundsExceptio
n");
     }
     catch(Exception e){
        System.out.println("Warning: Some Other exception");
     }
   System.out.println("Out of try-catch block...");
  }
}
Output:
Warning: ArithmeticException
Out of try-catch block..
Department of INformation Technology,URCW
In Java, using a try block inside another try block is permitted. It is
called as nested try block.
For example, the 
inner try block
 can be used to
handle 
ArrayIndexOutOfBoundsException
 while the 
outer try
block
 can handle the 
ArithemeticException
 (division by zero).
Why use nested try block
Sometimes a situation may arise where a part of a block may
cause one error and the entire block itself may cause another
error. In such cases, exception handlers have to be nested.
Java Nested try block
Department of INformation Technology,URCW
//main try block
try
{
    statement 1;
    statement 2;
//try catch block within another try block
    
try
    {
        statement 3;
        statement 4;
//try catch block within nested try block
        
try
        {
            statement 5;
            statement 6;
     }
        
catch
(Exception e2)
        {
//exception message
        }
    }
    
catch
(Exception e1)
    {
//exception message
    }
}
//catch block of parent (outer) try block
catch
(Exception e3)
{
//exception message
}
....
 
Department of INformation Technology,URCW
 
 
public class NestedTryBlock{
 public static void main(String args[]){
try{
      try{
     System.out.println("going to divide by 0");
     int b =39/0;
   }
catch(ArithmeticException e)
    {  System.out.println(e);
    }
    //inner try block 2
    try{
    int a[]=new int[5];
    a[5]=4;
     }
    catch(ArrayIndexOutOfBoundsException e)
    {   System.out.println(e);     }
    System.out.println("other statement");
  }
    catch(Exception e)
  {      System.out.println("handled the exception (outer catch)");   }
  System.out.println("normal flow..");
 }
}
Department of INformation Technology,URCW
undefined
Output
Department of INformation Technology,URCW
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.
Java finally block
Department of INformation Technology,URCW
finally block in Java can be used to put "
cleanup
"
code such as closing a file, closing connection, etc.
The important statements to be printed can be
placed in the finally block
Why use Java finally block?
Department of INformation Technology,URCW
Flowchart of finally block
Department of INformation Technology,URCW
The Java throw keyword is used to throw an exception
explicitly.
We specify the 
exception
 object which is to be thrown. The
Exception has some message with it that provides the
error description. These exceptions may be related to user
inputs, server, etc.
We can throw either checked or unchecked exceptions in
Java by throw keyword. It is mainly used to throw a
custom exception.
Java throw keyword
Department of INformation Technology,URCW
undefined
public class TestThrow1 {
    //function to check if person is eligible to vote or not
    public static void validate(int age) {
        if(age<18) {
            //throw Arithmetic exception if not eligible to vote
            throw new ArithmeticException("Person is not eligible
to vote");
        }
        else {
            System.out.println("Person is eligible to vote!!");
        }
    }
    //main method
    public static void main(String args[]){
        //calling the function
        validate(13);
        System.out.println("rest of the code...");
  }
}
Department of INformation Technology,URCW
Output
Department of INformation Technology,URCW
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.
Java throws keyword
Department of INformation Technology,URCW
public
 
class
 TestThrows {
    //defining a method
    
public
 
static
 
int
 divideNum(
int
 m, 
int
 n) 
throws
 ArithmeticException {
        
int
 div = m / n;
        
return
 div;
    }
    //main method
    
public
 
static
 
void
 main(String[] args) {
        TestThrows obj = 
new
 TestThrows();
        
try
 {
            System.out.println(obj.divideNum(45, 0));
        }
        
catch
 (ArithmeticException e){
            System.out.println("\nNumber cannot be divided by 0");
        }
        System.out.println("Rest of the code..");
    }
}
Java throws Example
Department of INformation Technology,URCW
ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
ArrayIndexOutOfBoundsException 
It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative
or greater than or equal to the size of the array.
ClassNotFoundException 
This Exception is raised when we try to access a class whose definition is not found
FileNotFoundException 
This Exception is raised when a file is not accessible or does not open.
IOException 
It is thrown when an input-output operation failed or interrupted
InterruptedException 
It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
NoSuchFieldException 
It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException 
It is thrown when accessing a method which is not found.
NullPointerException 
This exception is raised when referring to the members of a null object. Null represents nothing
NumberFormatException 
This exception is raised when a method could not convert a string into a numeric format.
RuntimeException 
This represents any exception which occurs during runtime.
StringIndexOutOfBoundsException 
It is thrown by String class methods to indicate that an index is either negative or greater than the size
of the string
Important Exceptions
Department of INformation Technology,URCW
Exception Hierarchy
Department of INformation Technology,URCW
// Java program to demonstrate ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo
{
 
public static void main(String args[])
 
{
  
try{
   
int a[] = new int[5];
   
a[6] = 9; // accessing 7th element in an
array of
     
// size 5
  
}
  
catch(ArrayIndexOutOfBoundsException e){
   
System.out.println ("Array Index is Out
Of Bounds");
  
}
 
}
}
 
ArrayIndexOutOfBound
Exception
Department of INformation Technology,URCW
Slide Note
Embed
Share

Understanding the concept of exception handling in Java, including what exceptions are, the difference between errors and exceptions, reasons for exceptions, how to handle them, and the advantages of exception handling. This topic covers the basics of handling runtime errors in Java programming and the importance of maintaining the normal flow of applications.

  • Java Exception Handling
  • Error vs Exception
  • Exception Reasons
  • Handling Mechanism
  • Importance of Exceptions

Uploaded on Nov 23, 2024 | 1 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Dr.Umayal Ramanathan College for Women Affiliated to Alagappa University, Karaikudi Accredited with B+ Grade by NAAC Department of Information TechnologY Java programming 7BIT2C1 Unit IV- Exception Handling Dr.L.Visalatchi Associate Professor Department of IT Department of INformation Technology,URCW

  2. Exception Handling What is an Exception? Difference between error and exception? How to do Exception handling? - Keywords Important Exceptions. Exception Hierarchy Example program Department of INformation Technology,URCW

  3. What is an Exception in java? Exception is an abnormal condition. In Java, an exception is an event that disrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message. Department of INformation Technology,URCW

  4. Why an exception occurs? There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc. Department of INformation Technology,URCW

  5. Why do we handle Exception Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. It is handled as an object which is thrown at runtime. 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. Department of INformation Technology,URCW

  6. Difference between Error and Exception Error: Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc. Exception: Exceptions are recoverable and could be handled. Department of INformation Technology,URCW

  7. Keywords in handling Exception try: The "try" keyword is used to specify a block where we should exception code. It means we can't use try block alone. The try block must be followed by either catch or finally. catch: The "catch" block is used to handle the exception. It must be by try block which means we can't use catch block block later. finally:The "finally" block is used to execute the necessary code of program. It is executed whether an exception is handled or throw: The "throw" keyword is used to throw an exception. throws: The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature. place an preceded alone. It can be followed by finally the not. Department of INformation Technology,URCW

  8. Steps in Exception handling Syntax of try catch in java try { //statements that may cause an exception } catch (exception(type) e(object)) { //error handling code } Department of INformation Technology,URCW

  9. public class JavaExceptionExample{ public static void main(String args[]) { try{ //codethat may raise exception int data=100/0; }catch(ArithmeticException e) { System.out.println(e); } //rest code of the program System.out.println("restof the code..."); } } Output: Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code... Department of INformation Technology,URCW

  10. Multiple catch blocks in Java A single try block can have any number of catch blocks. A generic catch block can handle all the exceptions. ArrayIndexOutOfBoundsException ArithmeticException ,NullPointerException or any other type of exception, this handles all of them. Department of INformation Technology,URCW

  11. Flow chart for multiple catch Department of INformation Technology,URCW

  12. class Example2{ public static void main(String args[]){ try{ int a[]=new int[7]; a[4]=30/0; System.out.println("First print statement in try block"); } catch(ArithmeticException e){ System.out.println("Warning:ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Warning:ArrayIndexOutOfBoundsExceptio n"); } catch(Exception e){ System.out.println("Warning: Some Other exception"); } System.out.println("Out of try-catch block..."); } } Output: Warning: ArithmeticException Out of try-catch block.. Department of INformation Technology,URCW

  13. Java Nested try block In Java, using a try block inside another try block is permitted. It is called as nested try block. For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can handle the ArithemeticException (division by zero). Why use nested try block Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested. Department of INformation Technology,URCW

  14. //main try block try { statement 1; statement 2; //try catch block within another try block try { statement 3; statement 4; //try catch block within nested try block try { statement 5; statement 6; } catch(Exception e2) { //exception message } } catch(Exception e1) { //exception message } } //catch block of parent (outer) try block catch(Exception e3) { //exception message } .... Department of INformation Technology,URCW

  15. public class NestedTryBlock{ public static void main(String args[]){ try{ try{ System.out.println("going to divide by 0"); int b =39/0; } catch(ArithmeticException e) { System.out.println(e); } //inner try block 2 try{ int a[]=new int[5]; a[5]=4; } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("other statement"); } catch(Exception e) { System.out.println("handled the exception (outer catch)"); } System.out.println("normal flow.."); } } Department of INformation Technology,URCW

  16. Output Department of INformation Technology,URCW

  17. 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. Department of INformation Technology,URCW

  18. Why use Java finally block? finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc. The important statements to be printed can be placed in the finally block Department of INformation Technology,URCW

  19. Flowchart of finally block Department of INformation Technology,URCW

  20. Java throw keyword The Java throw keyword is used to throw an exception explicitly. We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc. We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception. Department of INformation Technology,URCW

  21. public class TestThrow1 { //function to check if person is eligible to vote or not public static void validate(int age) { if(age<18) { //throw Arithmetic exception if not eligible to vote throw new ArithmeticException("Person is not eligible to vote"); } else { System.out.println("Person is eligible to vote!!"); } } //main method public static void main(String args[]){ //calling the function validate(13); System.out.println("rest of the code..."); } } Department of INformation Technology,URCW

  22. Output Department of INformation Technology,URCW

  23. Java throws keyword 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. Department of INformation Technology,URCW

  24. Java throws Example public class TestThrows { //defining a method public static int divideNum(intm, int n) throws ArithmeticException{ int div = m / n; return div; } //main method public static void main(String[] args){ TestThrows obj = newTestThrows(); try { System.out.println(obj.divideNum(45,0)); } catch (ArithmeticException e){ System.out.println("\nNumber cannot be dividedby 0"); } System.out.println("Restof the code.."); } } Department of INformation Technology,URCW

  25. Important Exceptions ArithmeticException It is thrown when an exceptional condition has occurred in an arithmetic operation. ArrayIndexOutOfBoundsException It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array. ClassNotFoundException This Exception is raised when we try to access a class whose definition is not found FileNotFoundException This Exception is raised when a file is not accessible or does not open. IOException It is thrown when an input-output operation failed or interrupted InterruptedException It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted. NoSuchFieldException It is thrown when a class does not contain the field (or variable) specified NoSuchMethodException It is thrown when accessing a method which is not found. NullPointerException This exception is raised when referring to the members of a null object. Null represents nothing NumberFormatException This exception is raised when a method could not convert a string into a numeric format. RuntimeException This represents any exception which occurs during runtime. StringIndexOutOfBoundsException It is thrown by String class methods to indicate that an index is either negative or greater than the size of the string Department of INformation Technology,URCW

  26. Exception Hierarchy Department of INformation Technology,URCW

  27. ArrayIndexOutOfBound Exception // Java program to demonstrate ArrayIndexOutOfBoundException class ArrayIndexOutOfBound_Demo { public static void main(String args[]) { try{ int a[] = new int[5]; a[6] = 9; // accessing 7th element in an array of } catch(ArrayIndexOutOfBoundsException e){ System.out.println ("Array Index is Out Of Bounds"); } } } Department of INformation Technology,URCW // size 5

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#