SlideShare a Scribd company logo
Exception Handling in
Java
www.tothenew.com
Agenda
❖ Errors & Exceptions
❖ Stack Trace
❖ Types of Exceptions
❖ Exception Handling
❖ try-catch-finally blocks
❖ try with resources
❖ Multiple Exceptions in Single Catch
❖ Advantages of Exception Handling
❖ Custom exceptions
www.tothenew.com
Exceptions
➔ An "exceptional condition" that alters the normal program flow
➔ Derive from class Exception
➔ Exception is said to be "thrown" and an Exception Handler "catches" it
➔ Includes File Not Found, Network connection was lost, etc.
Errors
➔ Represent unusual situations that are not caused by, and are external
to, the application
➔ Application won't be able to recover from an Error, so these aren't
required to handle
➔ Includes JVM running out of memory, hardware error, etc
www.tothenew.com
Stack Trace
➔ A list of the method calls that the application was in the middle of when an
Exception was thrown.
➔ Example : Book.java
public String getTitle() {
System.out.println(title.toString()); <-- line 16
return title;
}
➔ Exception in thread "main" java.lang.NullPointerException
at com.example.myproject.Book.getTitle(Book.java:16)
at com.example.myproject.Author.getBookTitles(Author.java:25)
at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
www.tothenew.com
What exception is not
➔ Exception is not a Message to be shown in the UI
➔ Exceptions are for programmers and support staff.
➔ For displaying in UI use externalized strings
www.tothenew.com
Types of Exceptions
➔ Checked Exceptions
◆ Checked at compile time
◆ Must be either handled or
specified using throws keyword
➔ Unchecked Exceptions
◆ Not checked at compile time
◆ Also called as Runtime Exceptions
www.tothenew.com
Checked Exception Example
➔ import java.io.*;
class Main {
public static void main(String[] args) {
FileReader file = new FileReader("a.txt");
BufferedReader fileInput = new BufferedReader(file);
}
}
➔ Compilation Error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code -
unreported exception java.io.FileNotFoundException; must be caught or declared to be
thrown
at Main.main(Main.java:5)
www.tothenew.com
Runtime Exception Example
➔ class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
➔ Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
Java Result: 1
www.tothenew.com
Exception Handling
➔ Mechanism to handle runtime malfunctions
➔ Transferring the execution of a program to an appropriate exception
handler when an exception occurs
Java Exception Handling Keywords
◆ try
◆ catch
◆ finally
◆ throw
◆ throws
www.tothenew.com
try-catch blocks
➔ try block :
◆ Used to enclose the code that might throw an exception.
◆ Must be used within the method.
◆ Java try block must be followed by either catch or finally block.
➔ catch block
◆ Java catch block is used to handle the Exception. It must be used after the
try block only.
◆ You can use multiple catch block with a single try.
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){
}
www.tothenew.com
Example
public class Testtrycatch{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("Executing rest of the code...");
}
}
Output :
Exception in thread main java.lang.ArithmeticException:/ by zero
Executing rest of the code...
www.tothenew.com
finally block
➔ Follows a try block.
➔ Always executes, whether or not an exception has occurred.
➔ Allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.
➔ Executes right before the return executes present in try block.
Syntax of try-finally block:
try{
// Protected Code that may throw exception
}catch(Exception ex){
// Catch block may or may not execute
}finally{
// The finally block always executes.
}
www.tothenew.com
Try with resources
➔ JDK 7 introduces a new version of try statement known as try-with-
resources statement. This feature add another way to exception handling
with resources management,it is also referred to as automatic resource
management.
try(resource-specification)
{
//use the resource
}catch()
{...}
www.tothenew.com
Multi catch block
➔ To perform different tasks at the occurrence of different Exceptions
➔ At a time only one Exception is occurred and at a time only one catch block is executed.
➔ All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException
must come before catch for Exception
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...");
}
}
Output:
task1 completed
rest of the code...
www.tothenew.com
Multiple Exceptions in Single Catch
Since Java 7, more than one exceptions can be handled using a single catch block
try{
// Code that may throw exception
} catch (IOException|FileNotFoundException ex) {
logger.log(ex);
}
Bytecode generated by compiling a catch block that handles multiple exception
types will be smaller (and thus superior) than 2 different catch blocks.
www.tothenew.com
throw keyword
➔ throw :
◆ Used to explicitly throw an exception
◆ Can be used to throw checked, unchecked and custom exception
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...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
www.tothenew.com
throws keyword
➔ throws :
◆ Used to declare an exception
◆ 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.
import java.io.IOException;
class Testthrows{
void secondMethod() throws IOException {
throw new IOException("device error");//checked exception
}
void firstMethod() throws IOException {
secondMethod();
}
public static void main(final String args[]) {
final Testthrows obj = new Testthrows();
try {
obj.firstMethod();
} catch (final Exception e) {
System.out.println("exception handled");
}
System.out.println("normal flow...");
}
Output:
exception handled
normal flow...
www.tothenew.com
Exception Handling with Method Overriding
➔ If the superclass method does not declare an exception, subclass overridden method cannot declare the
checked exception but it can declare unchecked exception.
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class TestExceptionChild extends Parent{
void msg()throws IOException{
System.out.println("TestExceptionChild");
}
public static void main(String args[]){
Parent parent=new TestExceptionChild();
parent.msg();
}
}
Output:
Compile Time Error
import java.io.*;
class Parent{
void msg(){System.out.println("parent");}
}
class TestExceptionChild1 extends Parent{
void msg()throws ArithmeticException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new TestExceptionChild1();
p.msg();
}
}
Output:
child
www.tothenew.com
Exception Handling with Method Overriding
➔ If the superclass method declares an exception, subclass overridden method can declare same, subclass
exception or no exception but cannot declare parent exception.
import java.io.*;
class Parent{
void msg()throws ArithmeticException{System.out.println("parent");}
}
class TestExceptionChild extends Parent{
void msg()throws Exception{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild();
try{
p.msg();
}catch(Exception e){}
}
}
Output:
Compile Time Error
import java.io.*;
class Parent{
void msg()throws Exception{System.out.println("parent");}
}
class TestExceptionChild1 extends Parent{
void msg()throws ArithmeticException{System.out.println("child");}
public static void main(String args[]){
Parent p=new TestExceptionChild1();
try{
p.msg();
}catch(Exception e){}
}
}
Output:
child
www.tothenew.com
Advantages of Exception Handling
➔ To maintain the normal flow of the application
➔ Separating Error-Handling Code from "Regular" Code
➔ Propagating Errors Up the Call Stack
➔ Grouping and Differentiating Error Types
www.tothenew.com
Custom Exceptions
➔ If you are creating your own Exception that is known as custom
exception or user-defined exception. Java custom exceptions are used to
customize the exception according to user need.
➔ By the help of custom exception, you can have your own exception and
message.
➔ To create a custom checked exception, we have to sub-class from the
java.lang.Exception class. And that’s it! Yes, creating a custom exception in
java is simple as that!
public class CustomException extends Exception{}
Java - Exception Handling

More Related Content

PPSX
Exception Handling
PDF
Java exception handling ppt
PPT
Java exception
PPT
Abstract class in java
PPS
Java Exception handling
PDF
Exception handling
PDF
Creating your own exception
PPT
Exception Handling in JAVA
Exception Handling
Java exception handling ppt
Java exception
Abstract class in java
Java Exception handling
Exception handling
Creating your own exception
Exception Handling in JAVA

What's hot (20)

PPTX
Exception handling in Java
PPTX
Exception handling in JAVA
PDF
Java I/o streams
PPTX
Constructor in java
PPTX
Exceptionhandling
PPTX
Exception handling
PPTX
Exception Handling in Java
PPTX
L14 exception handling
PPT
Generics in java
PPTX
Presentation on-exception-handling
PPTX
Exception handling in Java
PPTX
Access specifiers(modifiers) in java
PPTX
Control statements in java
PPTX
Exception handling in java
PDF
Methods in Java
PDF
Exception Handling in Java
PPTX
Java swing
PDF
Arrays in Java
PPTX
Java exception handling
Exception handling in Java
Exception handling in JAVA
Java I/o streams
Constructor in java
Exceptionhandling
Exception handling
Exception Handling in Java
L14 exception handling
Generics in java
Presentation on-exception-handling
Exception handling in Java
Access specifiers(modifiers) in java
Control statements in java
Exception handling in java
Methods in Java
Exception Handling in Java
Java swing
Arrays in Java
Java exception handling
Ad

Viewers also liked (7)

PPT
PDF
Java Pitfalls and Good-to-Knows
PPT
Exception Handling Java
PPTX
Exception handling
ODP
Exception handling in java
PPT
12 exception handling
PPTX
Exception handling in Java
Java Pitfalls and Good-to-Knows
Exception Handling Java
Exception handling
Exception handling in java
12 exception handling
Exception handling in Java
Ad

Similar to Java - Exception Handling (20)

PPTX
Exception handling in java
PPTX
Unit 4 exceptions and threads
PPTX
Exception handling in java
PPTX
Exception handling
PPTX
Exception Handling In Java Presentation. 2024
PPTX
Java-Exception Handling Presentation. 2024
PPTX
Unit II Java & J2EE regarding Java application development
PPTX
presentation-on-exception-handling 1.pptx
PPTX
presentation-on-exception-handling-160611180456 (1).pptx
PPT
Exception handling in java
PPTX
Pi j4.2 software-reliability
PPTX
Exceptions handling in java
PPTX
Exception Handling,finally,catch,throw,throws,try.pptx
PDF
Exception Handling notes in java exception
PDF
JAVA UNIT-2 ONE SHOT NOTES_64156529_2025_07_12_10__250712_103642.pdf
PDF
JAVA UNIT-2 ONE SHOT NOTES_64156529_2025_07_12_10__250712_103642.pdf
PPTX
Nalinee java
PPT
Exceptions
DOCX
Exception handling in java
PPT
Exception Handling
Exception handling in java
Unit 4 exceptions and threads
Exception handling in java
Exception handling
Exception Handling In Java Presentation. 2024
Java-Exception Handling Presentation. 2024
Unit II Java & J2EE regarding Java application development
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling-160611180456 (1).pptx
Exception handling in java
Pi j4.2 software-reliability
Exceptions handling in java
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling notes in java exception
JAVA UNIT-2 ONE SHOT NOTES_64156529_2025_07_12_10__250712_103642.pdf
JAVA UNIT-2 ONE SHOT NOTES_64156529_2025_07_12_10__250712_103642.pdf
Nalinee java
Exceptions
Exception handling in java
Exception Handling

Recently uploaded (20)

PPTX
ai tools demonstartion for schools and inter college
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Digital Strategies for Manufacturing Companies
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
medical staffing services at VALiNTRY
PDF
System and Network Administraation Chapter 3
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Nekopoi APK 2025 free lastest update
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
ai tools demonstartion for schools and inter college
Upgrade and Innovation Strategies for SAP ERP Customers
Operating system designcfffgfgggggggvggggggggg
Digital Strategies for Manufacturing Companies
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
medical staffing services at VALiNTRY
System and Network Administraation Chapter 3
Odoo POS Development Services by CandidRoot Solutions
wealthsignaloriginal-com-DS-text-... (1).pdf
Navsoft: AI-Powered Business Solutions & Custom Software Development
Which alternative to Crystal Reports is best for small or large businesses.pdf
How to Migrate SBCGlobal Email to Yahoo Easily
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Nekopoi APK 2025 free lastest update
How to Choose the Right IT Partner for Your Business in Malaysia
VVF-Customer-Presentation2025-Ver1.9.pptx
CHAPTER 2 - PM Management and IT Context
Adobe Illustrator 28.6 Crack My Vision of Vector Design
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf

Java - Exception Handling

  • 2. www.tothenew.com Agenda ❖ Errors & Exceptions ❖ Stack Trace ❖ Types of Exceptions ❖ Exception Handling ❖ try-catch-finally blocks ❖ try with resources ❖ Multiple Exceptions in Single Catch ❖ Advantages of Exception Handling ❖ Custom exceptions
  • 3. www.tothenew.com Exceptions ➔ An "exceptional condition" that alters the normal program flow ➔ Derive from class Exception ➔ Exception is said to be "thrown" and an Exception Handler "catches" it ➔ Includes File Not Found, Network connection was lost, etc. Errors ➔ Represent unusual situations that are not caused by, and are external to, the application ➔ Application won't be able to recover from an Error, so these aren't required to handle ➔ Includes JVM running out of memory, hardware error, etc
  • 4. www.tothenew.com Stack Trace ➔ A list of the method calls that the application was in the middle of when an Exception was thrown. ➔ Example : Book.java public String getTitle() { System.out.println(title.toString()); <-- line 16 return title; } ➔ Exception in thread "main" java.lang.NullPointerException at com.example.myproject.Book.getTitle(Book.java:16) at com.example.myproject.Author.getBookTitles(Author.java:25) at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
  • 5. www.tothenew.com What exception is not ➔ Exception is not a Message to be shown in the UI ➔ Exceptions are for programmers and support staff. ➔ For displaying in UI use externalized strings
  • 6. www.tothenew.com Types of Exceptions ➔ Checked Exceptions ◆ Checked at compile time ◆ Must be either handled or specified using throws keyword ➔ Unchecked Exceptions ◆ Not checked at compile time ◆ Also called as Runtime Exceptions
  • 7. www.tothenew.com Checked Exception Example ➔ import java.io.*; class Main { public static void main(String[] args) { FileReader file = new FileReader("a.txt"); BufferedReader fileInput = new BufferedReader(file); } } ➔ Compilation Error: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown at Main.main(Main.java:5)
  • 8. www.tothenew.com Runtime Exception Example ➔ class Main { public static void main(String args[]) { int x = 0; int y = 10; int z = y/x; } } ➔ Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:5) Java Result: 1
  • 9. www.tothenew.com Exception Handling ➔ Mechanism to handle runtime malfunctions ➔ Transferring the execution of a program to an appropriate exception handler when an exception occurs Java Exception Handling Keywords ◆ try ◆ catch ◆ finally ◆ throw ◆ throws
  • 10. www.tothenew.com try-catch blocks ➔ try block : ◆ Used to enclose the code that might throw an exception. ◆ Must be used within the method. ◆ Java try block must be followed by either catch or finally block. ➔ catch block ◆ Java catch block is used to handle the Exception. It must be used after the try block only. ◆ You can use multiple catch block with a single try. Syntax of java try-catch try{ //code that may throw exception }catch(Exception_class_Name ref){ }
  • 11. www.tothenew.com Example public class Testtrycatch{ public static void main(String args[]){ try{ int data=50/0; }catch(ArithmeticException e){ System.out.println(e); } System.out.println("Executing rest of the code..."); } } Output : Exception in thread main java.lang.ArithmeticException:/ by zero Executing rest of the code...
  • 12. www.tothenew.com finally block ➔ Follows a try block. ➔ Always executes, whether or not an exception has occurred. ➔ Allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. ➔ Executes right before the return executes present in try block. Syntax of try-finally block: try{ // Protected Code that may throw exception }catch(Exception ex){ // Catch block may or may not execute }finally{ // The finally block always executes. }
  • 13. www.tothenew.com Try with resources ➔ JDK 7 introduces a new version of try statement known as try-with- resources statement. This feature add another way to exception handling with resources management,it is also referred to as automatic resource management. try(resource-specification) { //use the resource }catch() {...}
  • 14. www.tothenew.com Multi catch block ➔ To perform different tasks at the occurrence of different Exceptions ➔ At a time only one Exception is occurred and at a time only one catch block is executed. ➔ All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception 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..."); } } Output: task1 completed rest of the code...
  • 15. www.tothenew.com Multiple Exceptions in Single Catch Since Java 7, more than one exceptions can be handled using a single catch block try{ // Code that may throw exception } catch (IOException|FileNotFoundException ex) { logger.log(ex); } Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than 2 different catch blocks.
  • 16. www.tothenew.com throw keyword ➔ throw : ◆ Used to explicitly throw an exception ◆ Can be used to throw checked, unchecked and custom exception 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..."); } } Output: Exception in thread main java.lang.ArithmeticException:not valid
  • 17. www.tothenew.com throws keyword ➔ throws : ◆ Used to declare an exception ◆ 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. import java.io.IOException; class Testthrows{ void secondMethod() throws IOException { throw new IOException("device error");//checked exception } void firstMethod() throws IOException { secondMethod(); } public static void main(final String args[]) { final Testthrows obj = new Testthrows(); try { obj.firstMethod(); } catch (final Exception e) { System.out.println("exception handled"); } System.out.println("normal flow..."); } Output: exception handled normal flow...
  • 18. www.tothenew.com Exception Handling with Method Overriding ➔ If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception. import java.io.*; class Parent{ void msg(){System.out.println("parent");} } class TestExceptionChild extends Parent{ void msg()throws IOException{ System.out.println("TestExceptionChild"); } public static void main(String args[]){ Parent parent=new TestExceptionChild(); parent.msg(); } } Output: Compile Time Error import java.io.*; class Parent{ void msg(){System.out.println("parent");} } class TestExceptionChild1 extends Parent{ void msg()throws ArithmeticException{ System.out.println("child"); } public static void main(String args[]){ Parent p=new TestExceptionChild1(); p.msg(); } } Output: child
  • 19. www.tothenew.com Exception Handling with Method Overriding ➔ If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. import java.io.*; class Parent{ void msg()throws ArithmeticException{System.out.println("parent");} } class TestExceptionChild extends Parent{ void msg()throws Exception{System.out.println("child");} public static void main(String args[]){ Parent p=new TestExceptionChild(); try{ p.msg(); }catch(Exception e){} } } Output: Compile Time Error import java.io.*; class Parent{ void msg()throws Exception{System.out.println("parent");} } class TestExceptionChild1 extends Parent{ void msg()throws ArithmeticException{System.out.println("child");} public static void main(String args[]){ Parent p=new TestExceptionChild1(); try{ p.msg(); }catch(Exception e){} } } Output: child
  • 20. www.tothenew.com Advantages of Exception Handling ➔ To maintain the normal flow of the application ➔ Separating Error-Handling Code from "Regular" Code ➔ Propagating Errors Up the Call Stack ➔ Grouping and Differentiating Error Types
  • 21. www.tothenew.com Custom Exceptions ➔ If you are creating your own Exception that is known as custom exception or user-defined exception. Java custom exceptions are used to customize the exception according to user need. ➔ By the help of custom exception, you can have your own exception and message. ➔ To create a custom checked exception, we have to sub-class from the java.lang.Exception class. And that’s it! Yes, creating a custom exception in java is simple as that! public class CustomException extends Exception{}