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

PDF
Java exception handling ppt
PPTX
Java exception handling
PPTX
Control statements in java
PPTX
Exception Handling in object oriented programming using C++
PPT
Java Servlets
PPT
Switch statements in Java
PPTX
Exception Handling in Java
PPTX
Strings in Java
Java exception handling ppt
Java exception handling
Control statements in java
Exception Handling in object oriented programming using C++
Java Servlets
Switch statements in Java
Exception Handling in Java
Strings in Java

What's hot (20)

PPTX
Presentation on-exception-handling
PPTX
Arrays in Java
PPTX
Event handling
PPTX
Interface in java
PPTX
Exception handling in java
PDF
Arrays in Java
PPTX
Static Members-Java.pptx
PPT
Menu bars and menus
PPTX
Exception handling in Java
PPTX
Servlets
PPTX
JAVA AWT
PPT
Java And Multithreading
PPTX
Event Handling in java
PPTX
This keyword in java
PPTX
Error managing and exception handling in java
PPTX
Java Data Types
PPTX
Data types in java
PPT
PPTX
Java Beans
PPTX
Event In JavaScript
Presentation on-exception-handling
Arrays in Java
Event handling
Interface in java
Exception handling in java
Arrays in Java
Static Members-Java.pptx
Menu bars and menus
Exception handling in Java
Servlets
JAVA AWT
Java And Multithreading
Event Handling in java
This keyword in java
Error managing and exception handling in java
Java Data Types
Data types in java
Java Beans
Event In JavaScript
Ad

Viewers also liked (9)

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

Similar to Java - Exception Handling (20)

PDF
Exception handling
PDF
Exception handling
PDF
Java Day-5
DOCX
Java Exception handling
PPTX
Exception‐Handling in object oriented programming
PPTX
presentation-on-exception-handling 1.pptx
PPTX
presentation-on-exception-handling-160611180456 (1).pptx
PPTX
Exception handling in java-PPT.pptx
PPTX
Exception Handling In Java Presentation. 2024
PPTX
Java-Exception Handling Presentation. 2024
PPTX
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
PPT
Exception Handling Exception Handling Exception Handling
PPTX
130410107010 exception handling
PPTX
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
PPT
Exceptionhandling
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
Exception handling
Exception handling
Java Day-5
Java Exception handling
Exception‐Handling in object oriented programming
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling-160611180456 (1).pptx
Exception handling in java-PPT.pptx
Exception Handling In Java Presentation. 2024
Java-Exception Handling Presentation. 2024
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
Exception Handling Exception Handling Exception Handling
130410107010 exception handling
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exceptionhandling
Exception
Exception
Exception
Exception
Exception

Recently uploaded (20)

PPTX
Phoenix Marketo User Group: Building Nurtures that Work for Your Audience. An...
PDF
Difference Between Website and Web Application.pdf
PPTX
Greedy best-first search algorithm always selects the path which appears best...
PDF
MaterialX Virtual Town Hall - August 2025
PPTX
TRAVEL SUPPLIER API INTEGRATION | XML BOOKING ENGINE
PDF
OpenImageIO Virtual Town Hall - August 2025
PDF
KidsTale AI Review - Create Magical Kids’ Story Videos in 2 Minutes.pdf
PPTX
Comprehensive Guide to Digital Image Processing Concepts and Applications
PDF
C language slides for c programming book by ANSI
PDF
Science is Not Enough SPLC2009 Richard P. Gabriel
PPTX
AI Tools Revolutionizing Software Development Workflows
PDF
DOWNLOAD—IOBit Uninstaller Pro Crack Download Free
PPTX
Beige and Black Minimalist Project Deck Presentation (1).pptx
PDF
WhatsApp Chatbots The Key to Scalable Customer Support.pdf
PDF
OpenEXR Virtual Town Hall - August 2025
PDF
10 Mistakes Agile Project Managers Still Make
PPTX
ESDS_SAP Application Cloud Offerings.pptx
PPTX
Presentation - Summer Internship at Samatrix.io_template_2.pptx
PDF
4K Video Downloader Crack + License Key 2025
PPTX
MCP empowers AI Agents from Zero to Production
Phoenix Marketo User Group: Building Nurtures that Work for Your Audience. An...
Difference Between Website and Web Application.pdf
Greedy best-first search algorithm always selects the path which appears best...
MaterialX Virtual Town Hall - August 2025
TRAVEL SUPPLIER API INTEGRATION | XML BOOKING ENGINE
OpenImageIO Virtual Town Hall - August 2025
KidsTale AI Review - Create Magical Kids’ Story Videos in 2 Minutes.pdf
Comprehensive Guide to Digital Image Processing Concepts and Applications
C language slides for c programming book by ANSI
Science is Not Enough SPLC2009 Richard P. Gabriel
AI Tools Revolutionizing Software Development Workflows
DOWNLOAD—IOBit Uninstaller Pro Crack Download Free
Beige and Black Minimalist Project Deck Presentation (1).pptx
WhatsApp Chatbots The Key to Scalable Customer Support.pdf
OpenEXR Virtual Town Hall - August 2025
10 Mistakes Agile Project Managers Still Make
ESDS_SAP Application Cloud Offerings.pptx
Presentation - Summer Internship at Samatrix.io_template_2.pptx
4K Video Downloader Crack + License Key 2025
MCP empowers AI Agents from Zero to Production

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{}