SlideShare a Scribd company logo
13
Most read
22
Most read
23
Most read
Exception handling in java
Here, i will discuss what is an
exception and how it can be
handled in java programming
language.
An Exception can be anything which interrupts the normal
flow of the program. When an exception occurs program
processing gets terminated and doesn’t continue further.
In such cases we get a system generated error message. In
other words, an exception is a run-time error. The good
thing about exceptions is that they can be handled.
What is an exception?
Exception can occur at runtime (known as runtime exceptions) as
well as at compile-time (known Compile-time exceptions).
In example-
 Dividing a number by zero.
 Accessing an element that is out of bounds of an array.
 Trying to store incompatible data elements.
 Trying to convert from string to specific data value.
 File errors: not found, permissions error etc.
 Corrupting memory.
 Network connection error.
When an exception can occur?
 Exception handling allows us to control the normal flow of
the program by using exception handling in program.
 It throws an exception whenever a calling method
encounters an error providing that the calling method
takes care of that error.
 It also gives us the scope of organizing and differentiating
between different error types using a separate block of
codes. This is done with the help of try-catch blocks.
Advantages of Exception Handling
If an exception is raised, which has not been handled by programmer
then program execution can get terminated and system prints a non
user friendly error message.
We handle such conditions and then prints a user friendly warning
message to user, which lets them correct the error as most of the
time exception occurs due to bad data provided by user.
Why to handle exception?
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo : The class name
main : The method name
ExceptionDemo.java : The filename
java:5 : Line number
In computer languages that do not support exception
handling, errors must be checked and handled manually—
typically through the use of error codes, and so on. This
approach is as cumbersome as it is troublesome. Java’s
exception handling avoids these problems and, in the process,
brings run-time error management into the object oriented
world.
Exception Handling in Java
 ArithmeticException
 ArrayIndexOutOfBoundsExcep
tion
 NullPointerException
 NegativeArraySizeException
Unchecked exceptions
 ClassNotFoundException
 IllegalAccessException
 NoSuchFieldException
 EOFException
Checked exceptions
Types of exceptions in Java
Exception handling in java
1) try
2) catch
3) throw
4) throws
5) finally
Java Exception Handling Keywords
try {
// block of code to monitor for errors
// throw exception explicitly (mainly custom exception)
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
General Form of an Exception Handling Block
Java try block is used to enclose the code that might throw
an exception. It must be used within the method.
Possible forms of try statement:
1. try-catch
2. try-finally
3. try-catch-finally
If an exception occurs in a try statement, execution of the try
statement is terminated. A catch statement handles the
exeception thrown by the try statement.
Java try Block
Java catch block is used to handle the Exception. It must be
used after the try block only. If you have to perform
different tasks at the occurrence of different Exceptions,
use java multi catch block with a single try.
Rules for multiple catch block:
1. At a time only one Exception is occured and at a time only
one catch block is executed.
2. All catch blocks must be ordered from most specific to
most general i.e. catch for ArithmeticException must
come before catch for Exception .
Java catch Block
Internal
working
of java
try-catch
block
Task1 is completed
rest of the code

public class TestMultipleCatchBlock {
public static void main (String args[]) {
try {
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e) {
System.out.println("task1 is completed"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("task 2 completed"); }
catch(Exception e) {
System.out.println("common task completed"); }
System.out.println("rest of the code...");
}
}
Java finally block is a block that is used to execute
important code such as closing connection, stream etc. It is
always executed whether exception is handled or not. It
can be used to put "cleanup" code such as closing a file,
closing connection etc.
Rules for finally block:
1. For each try block there can be zero or more catch blocks,
but only one finally block.
2. The finally block will not be executed if program exits(either
by calling System.exit() or by causing a fatal error that causes
the process to abort).
Java finally Block
Internal
working
of java
try-catch-
finally
block
Task1 is completed
finally block is always executed
rest of the code

public class TestMultipleCatchBlock {
public static void main (String args[]) {
try {
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e) {
System.out.println("task1 is completed"); }
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("task 2 completed"); }
catch(Exception e) { System.out.println("common task completed"); }
finally { System.out.println(“finally block is always executed”); }
System.out.println("rest of the code...");
}
}
The Java throw keyword is used to explicitly throw an
exception mainly custom exception. We can throw either
checked or uncheked exception in java by throw keyword.
Syntax:
throw exception;
// throw custom exception
throw new IOException("sorry device error);
// throw IOException
Java throw Keyword
Exception in thread main java.lang.ArithmeticException:not valid
public class TestThrow1{
static void validate(int age) {
if(age<18) throw new ArithmeticException("not valid");
else System.out.println("welcome to vote");
}
public static void main(String args[]) {
validate(13);
System.out.println("rest of the code...");
}
}
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 normal flow can
be maintained.
Syntax:
return_type method_name() throws exception_class_name {
// method code
}
Java throws Keyword
No throw throws
1 Java throw keyword is used to
explicitly throw an exception.
Java throws keyword is used to declare
an exception.
2 Checked exception cannot be
propagated using throw only.
Checked exception can be propagated
with throws.
3 Throw is followed by an instance. Throws is followed by class.
4 Throw is used within the method. Throws is used with the method
signature.
5 You cannot throw multiple
exceptions.
You can declare multiple exceptions e.g.
public void method() throws
IOException,SQLException
Difference between throw and throws in Java
Md. Arafat Islam
Roll: 150126
Department of Computer Science and Engineering
Pabna University of Science and Technology
ThankYou

More Related Content

What's hot (20)

PPT
Exception handling in java
Pratik Soares
 
PPTX
Interface in java
PhD Research Scholar
 
PPTX
Exception handling
PhD Research Scholar
 
PPT
Java exception
Arati Gadgil
 
PPSX
Exception Handling
Reddhi Basu
 
PPTX
Exception handling in Java
Abhishek Pachisia
 
PPTX
Java exception handling
Md. Tanvir Hossain
 
PPTX
Exceptionhandling
Nuha Noor
 
PPTX
Exception handling in Java
Ankit Rai
 
PPT
Exception handling
Tata Consultancy Services
 
PPTX
6. static keyword
Indu Sharma Bhardwaj
 
PPTX
Method overloading
Lovely Professional University
 
PPTX
Java exception handling
BHUVIJAYAVELU
 
PPT
Exception Handling in JAVA
SURIT DATTA
 
PDF
Java IO
UTSAB NEUPANE
 
PPTX
Exception handling in JAVA
Kunal Singh
 
PDF
Java - Exception Handling Concepts
Victer Paul
 
PPT
Generics in java
suraj pandey
 
DOCX
Exceptions handling notes in JAVA
Sunil Kumar Gunasekaran
 
Exception handling in java
Pratik Soares
 
Interface in java
PhD Research Scholar
 
Exception handling
PhD Research Scholar
 
Java exception
Arati Gadgil
 
Exception Handling
Reddhi Basu
 
Exception handling in Java
Abhishek Pachisia
 
Java exception handling
Md. Tanvir Hossain
 
Exceptionhandling
Nuha Noor
 
Exception handling in Java
Ankit Rai
 
Exception handling
Tata Consultancy Services
 
6. static keyword
Indu Sharma Bhardwaj
 
Method overloading
Lovely Professional University
 
Java exception handling
BHUVIJAYAVELU
 
Exception Handling in JAVA
SURIT DATTA
 
Java IO
UTSAB NEUPANE
 
Exception handling in JAVA
Kunal Singh
 
Java - Exception Handling Concepts
Victer Paul
 
Generics in java
suraj pandey
 
Exceptions handling notes in JAVA
Sunil Kumar Gunasekaran
 

Similar to Exception handling in java (20)

PPTX
Exception handling in java.pptx
Nagaraju Pamarthi
 
PPTX
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
PPTX
UNIT 2.pptx
EduclentMegasoftel
 
PPTX
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
PPTX
Interface andexceptions
saman Iftikhar
 
PPTX
Exception Handling.pptx
primevideos176
 
PDF
Java unit 11
Shipra Swati
 
PPTX
Exception handling in java
Lovely Professional University
 
PPT
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
PPTX
Exceptions handling in java
junnubabu
 
PPT
Exceptionhandling
DrHemlathadhevi
 
PDF
JAVA PPT -4 BY ADI.pdf
Prof. Dr. K. Adisesha
 
PDF
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
PPTX
Exception handling
Ardhendu Nandi
 
PPTX
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
PPTX
Exception handling in java
Kavitha713564
 
PPT
Exception Handling in java masters of computer application
xidileh999
 
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
PPT
8.Exception handling latest(MB).ppt .
happycocoman
 
PPT
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
UNIT 2.pptx
EduclentMegasoftel
 
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
Interface andexceptions
saman Iftikhar
 
Exception Handling.pptx
primevideos176
 
Java unit 11
Shipra Swati
 
Exception handling in java
Lovely Professional University
 
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
Exceptions handling in java
junnubabu
 
Exceptionhandling
DrHemlathadhevi
 
JAVA PPT -4 BY ADI.pdf
Prof. Dr. K. Adisesha
 
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Exception handling
Ardhendu Nandi
 
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
Exception handling in java
Kavitha713564
 
Exception Handling in java masters of computer application
xidileh999
 
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
8.Exception handling latest(MB).ppt .
happycocoman
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Ad

Recently uploaded (20)

PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih KĂŒĂ§ĂŒk
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Tally software_Introduction_Presentation
AditiBansal54083
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih KĂŒĂ§ĂŒk
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...
logixshapers59
 
Ad

Exception handling in java

  • 2. Here, i will discuss what is an exception and how it can be handled in java programming language.
  • 3. An Exception can be anything which interrupts the normal flow of the program. When an exception occurs program processing gets terminated and doesn’t continue further. In such cases we get a system generated error message. In other words, an exception is a run-time error. The good thing about exceptions is that they can be handled. What is an exception?
  • 4. Exception can occur at runtime (known as runtime exceptions) as well as at compile-time (known Compile-time exceptions). In example-  Dividing a number by zero.  Accessing an element that is out of bounds of an array.  Trying to store incompatible data elements.  Trying to convert from string to specific data value.  File errors: not found, permissions error etc.  Corrupting memory.  Network connection error. When an exception can occur?
  • 5.  Exception handling allows us to control the normal flow of the program by using exception handling in program.  It throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error.  It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks. Advantages of Exception Handling
  • 6. If an exception is raised, which has not been handled by programmer then program execution can get terminated and system prints a non user friendly error message. We handle such conditions and then prints a user friendly warning message to user, which lets them correct the error as most of the time exception occurs due to bad data provided by user. Why to handle exception? Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:5) ExceptionDemo : The class name main : The method name ExceptionDemo.java : The filename java:5 : Line number
  • 7. In computer languages that do not support exception handling, errors must be checked and handled manually— typically through the use of error codes, and so on. This approach is as cumbersome as it is troublesome. Java’s exception handling avoids these problems and, in the process, brings run-time error management into the object oriented world. Exception Handling in Java
  • 8.  ArithmeticException  ArrayIndexOutOfBoundsExcep tion  NullPointerException  NegativeArraySizeException Unchecked exceptions  ClassNotFoundException  IllegalAccessException  NoSuchFieldException  EOFException Checked exceptions Types of exceptions in Java
  • 10. 1) try 2) catch 3) throw 4) throws 5) finally Java Exception Handling Keywords
  • 11. try { // block of code to monitor for errors // throw exception explicitly (mainly custom exception) } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed after try block ends } General Form of an Exception Handling Block
  • 12. Java try block is used to enclose the code that might throw an exception. It must be used within the method. Possible forms of try statement: 1. try-catch 2. try-finally 3. try-catch-finally If an exception occurs in a try statement, execution of the try statement is terminated. A catch statement handles the exeception thrown by the try statement. Java try Block
  • 13. Java catch block is used to handle the Exception. It must be used after the try block only. If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block with a single try. Rules for multiple catch block: 1. At a time only one Exception is occured and at a time only one catch block is executed. 2. All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception . Java catch Block
  • 15. Task1 is completed rest of the code
 public class TestMultipleCatchBlock { public static void main (String args[]) { try { int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) { System.out.println("task1 is completed"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("task 2 completed"); } catch(Exception e) { System.out.println("common task completed"); } System.out.println("rest of the code..."); } }
  • 16. Java finally block is a block that is used to execute important code such as closing connection, stream etc. It is always executed whether exception is handled or not. It can be used to put "cleanup" code such as closing a file, closing connection etc. Rules for finally block: 1. For each try block there can be zero or more catch blocks, but only one finally block. 2. The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort). Java finally Block
  • 18. Task1 is completed finally block is always executed rest of the code
 public class TestMultipleCatchBlock { public static void main (String args[]) { try { int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) { System.out.println("task1 is completed"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("task 2 completed"); } catch(Exception e) { System.out.println("common task completed"); } finally { System.out.println(“finally block is always executed”); } System.out.println("rest of the code..."); } }
  • 19. The Java throw keyword is used to explicitly throw an exception mainly custom exception. We can throw either checked or uncheked exception in java by throw keyword. Syntax: throw exception; // throw custom exception throw new IOException("sorry device error); // throw IOException Java throw Keyword
  • 20. Exception in thread main java.lang.ArithmeticException:not valid public class TestThrow1{ static void validate(int age) { if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]) { validate(13); System.out.println("rest of the code..."); } }
  • 21. 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 normal flow can be maintained. Syntax: return_type method_name() throws exception_class_name { // method code } Java throws Keyword
  • 22. No throw throws 1 Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception. 2 Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws. 3 Throw is followed by an instance. Throws is followed by class. 4 Throw is used within the method. Throws is used with the method signature. 5 You cannot throw multiple exceptions. You can declare multiple exceptions e.g. public void method() throws IOException,SQLException Difference between throw and throws in Java
  • 23. Md. Arafat Islam Roll: 150126 Department of Computer Science and Engineering Pabna University of Science and Technology