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

What's hot

L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Files in java
Files in javaFiles in java
Exception handling
Exception handling Exception handling
Exception handling
M Vishnuvardhan Reddy
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
Abir Mohammad
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
Ashita Agrawal
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
Surbhi Panhalkar
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Pavith Gunasekara
 
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)
Michelle Anne Meralpis
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
harsh kothari
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Java program structure
Java program structureJava program structure
Java program structure
shalinikarunakaran1
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
garishma bhatia
 

What's hot (20)

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
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
OOP java
OOP javaOOP java
OOP java
 
Files in java
Files in javaFiles in java
Files in java
 
Exception handling
Exception handling Exception handling
Exception handling
 
Java threads
Java threadsJava threads
Java threads
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
 
Constructor in java
Constructor in javaConstructor in java
Constructor 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)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java program structure
Java program structureJava program structure
Java program structure
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 

Viewers also liked

Exception
ExceptionException
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
Miquel Martin
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
ankitgarg_er
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaPrasad Sawant
 

Viewers also liked (8)

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

Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
Exception handling
Exception handlingException handling
Exception handling
SAIFUR RAHMAN
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
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 in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
mcollison
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
junnubabu
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
Nalinee Choudhary
 
Exceptions
ExceptionsExceptions
Exceptions
Soham Sengupta
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
GaneshKumarKanthiah
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
happycocoman
 

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
 
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
Exception HandlingException Handling
Exception Handling
 
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

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 

Recently uploaded (20)

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 

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