SlideShare a Scribd company logo
1 of 22
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

What's hot

Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 

What's hot (20)

Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Java program structure
Java program structureJava program structure
Java program structure
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Exception handling
Exception handlingException handling
Exception handling
 
Java Streams
Java StreamsJava Streams
Java Streams
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 

Viewers also liked (7)

Exception
ExceptionException
Exception
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 

Similar to Java - Exception Handling

Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Exception Handling
Exception HandlingException Handling
Exception Handling
backdoor
 

Similar to Java - Exception Handling (20)

Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Exceptions
ExceptionsExceptions
Exceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Recently uploaded (20)

Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.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{}