SlideShare a Scribd company logo
Exceptions in Java
What is an exception?
An exception is an error condition that changes the normal
flow of control in a program
Exceptions in Java separates error handling from main
business logic
Based on ideas developed in Ada, Eiffel and C++
Java has a uniform approach for handling all synchronous
errors
• From very unusual (e.g. out of memory)
• To more common ones your program should check itself (e.g. index out
of bounds)
• From Java run-time system errors (e.g., divide by zero)
• To errors that programmers detect and raise deliberately
Throwing and catching
An error can throw an exception
throw <exception object>;
By default, exceptions result in the thread
terminating after printing an error message
However, exception handlers can catch specified
exceptions and recover from error
catch (<exception type> e) {
//statements that handle the
exception
}
Throwing an exception
• Example creates a subclass of Exception and throws an exception:
class MyException extends Exception { }
class MyClass {
void oops()
{ if (/* no error occurred */)
{ /* normal processing */ }
else { /* error occurred */
throw new MyException();
}
} //oops
}//class MyClass
Exceptional flow of control
Exceptions break the normal flow of control.
When an exception occurs, the statement that
would normally execute next is not executed.
What happens instead depends on:
◦ whether the exception is caught,
◦ where it is caught,
◦ what statements are executed in the ‘catch block’,
◦ and whether you have a ‘finally block’.
Approaches to handling an exception
1. Prevent the exception from happening
2. Catch it in the method in which it occurs, and either
a. Fix up the problem and resume normal execution
b. Rethrow it
c. Throw a different exception
3. Declare that the method throws the exception
4. With 1. and 2.a. the caller never knows there was an error.
5. With 2.b., 2.c., and 3., if the caller does not handle the
exception, the program will terminate and display a stack
trace
Exception hierarchy
• Java organizes exceptions in inheritance tree:
– Throwable
– Error
– Exception
• RuntimeException
• TooManyListenersException
• IOException
• AWTException
Java is strict
Unlike C++, is quite strict about catching exceptions
If it is a checked exception
◦ (all except Error, RuntimeException and their subclasses),
◦ Java compiler forces the caller must either catch it
◦ or explicitly re-throw it with an exception specification.
Why is this a good idea?
By enforcing exception specifications from top to bottom, Java
guarantees exception correctness at compile time.
Here’s a method that ducks out of catching an exception by
explicitly re-throwing it:
void f() throws tooBig, tooSmall, divZero {
◦ The caller of this method now must either catch these exceptions or
rethrow them in its specification.
Error and RuntimeException
Error
◦ “unchecked”, thus need not be in ‘throws’ clause
◦ Serious system problems (e.g. ThreadDeath, OutOfMemoryError)
◦ It’s very unlikely that the program will be able to recover, so generally
you should NOT catch these.
RuntimeException
◦ “unchecked”, thus need not be in ‘throws’ clause
◦ Also can occur almost anywhere, e.g. ArithmeticException,
NullPointerException, IndexOutOfBoundsException
◦ Try to prevent them from happening in the first place!
System will print stop program and print a trace
Catching an exception
try { // statement that could throw an exception
}
catch (<exception type> e) {
// statements that handle the exception
}
catch (<exception type> e) { //e higher in hierarchy
// statements that handle the exception
}
finally {
// release resources
}
//other statements
• At most one catch block executes
• finally block always executes once, whether there’s an error or not
Execution of try catch blocks
• For normal execution:
– try block executes, then finally block executes, then other statements execute
• When an error is caught and the catch block throws an exception or returns:
– try block is interrupted
– catch block executes (until throw or return statement)
– finally block executes
• When error is caught and catch block doesn’t throw an exception or return:
– try block is interrupted
– catch block executes
– finally block executes
– other statements execute
• When an error occurs that is not caught:
– try block is interrupted
– finally block executes
Example:
try { p.a = 10; }
catch (NullPointerException e)
{ System.out.println("p was null"); }
catch (Exception e)
{ System.out.println("other error occurred"); }
catch (Object obj)
{ System.out.println("Who threw that object?"); }
finally { System.out.println(“final processing"); }
System.out.println(“Continue with more statements");
Catch processing
• When an exception occurs, the nested try/catch statements are searched
for a catch parameter matching the exception class
• A parameter is said to match the exception if it:
– is the same class as the exception; or
– is a superclass of the exception; or
– if the parameter is an interface, the exception class implements the interface.
• The first try/catch statement that has a parameter that matches the
exception has its catch statement executed.
• After the catch statement executes, execution resumes with the finally
statement, then the statements after the try/catch statement.
Catch processing example
print("now");   
try   
{ print("is ");      
  throw new MyException();     
  print("a ");   
} 
catch(MyException e)   { print("the ");   }   
print("timen"); 
• Prints "now is the time".
• Note that exceptions don't have to be used only for error handling
• Would it be a good idea to exceptions for non-error processing?
• But any other use is likely to result in code that's hard to understand.
Declaring an exception type
• Inherit from an existing exception type.
• Provide a default constructor
• and a constructor with one arg, type String.
• Both should call super(astring);
• Example:
class MyThrowable extends Throwable { 
// checked exception
  MyThrowable () {
     super ("Generated MyThrowable");
  }
  MyThrowable (String s) { super (s); }
}
Declaring an exception type
• Inherit from an existing exception type.
• Provide a default constructor
• and a constructor with one arg, type String.
• Both should call super(astring);
class ErrorThrower {
public void errorMethod() throws MyThrowable
{ throw new MyThrowable ("ErrorThrower");
// forces this method to declare MyThrowable
}
}
Exceptions are ubiquitous in Java
• Exception handling required for all read methods
– Also many other system methods
• If you use one of Java's built in class methods and it throws
an exception, you must catch it (i.e., surround it in a
try/catch block) or rethrow it, or you will get a compile
time error:
char ch;
try { ch = (char) System.in.read(); }
catch (IOException e)
{ System.err.println(e); return;

More Related Content

What's hot

Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
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 HandlingPrabhdeep Singh
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
parag
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
Kunal Singh
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
mcollison
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaPrasad Sawant
 
Exception handling in java
Exception handling  in javaException handling  in java
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
Hemant Chetwani
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
Tanmoy Roy
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
Exception handling
Exception handlingException handling
Exception handling
pooja kumari
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 

What's hot (20)

Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling
Exception handlingException handling
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 Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
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
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
 
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
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 

Similar to Exceptions in java

Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
Ashfaaq Mahroof
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
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
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
Prof. Dr. K. Adisesha
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statementmyrajendra
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
RanjithaM32
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
ARUNPRANESHS
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
Varshini62
 

Similar to Exceptions in java (20)

Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdfJAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Multi catch statement
Multi catch statementMulti catch statement
Multi catch statement
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
 

More from Rajkattamuri

Github plugin setup in anypointstudio
Github plugin setup in anypointstudioGithub plugin setup in anypointstudio
Github plugin setup in anypointstudio
Rajkattamuri
 
For each component in mule
For each component in muleFor each component in mule
For each component in mule
Rajkattamuri
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in mule
Rajkattamuri
 
File component in mule
File component in muleFile component in mule
File component in mule
Rajkattamuri
 
Database component in mule
Database component in muleDatabase component in mule
Database component in mule
Rajkattamuri
 
Choice component in mule
Choice component in mule Choice component in mule
Choice component in mule
Rajkattamuri
 
WebServices
WebServicesWebServices
WebServices
Rajkattamuri
 
Java Basics in Mule
Java Basics in MuleJava Basics in Mule
Java Basics in Mule
Rajkattamuri
 
WebServices Basic Overview
WebServices Basic OverviewWebServices Basic Overview
WebServices Basic Overview
Rajkattamuri
 
Java For Begineers
Java For BegineersJava For Begineers
Java For Begineers
Rajkattamuri
 
Java Basics
Java BasicsJava Basics
Java Basics
Rajkattamuri
 
WebServices Basics
WebServices BasicsWebServices Basics
WebServices Basics
Rajkattamuri
 
Core java
Core javaCore java
Core java
Rajkattamuri
 
WebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDIWebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDI
Rajkattamuri
 
Web services soap
Web services soapWeb services soap
Web services soap
Rajkattamuri
 
Web services wsdl
Web services wsdlWeb services wsdl
Web services wsdl
Rajkattamuri
 
Web services uddi
Web services uddiWeb services uddi
Web services uddi
Rajkattamuri
 
Maven
MavenMaven
Mule esb dataweave
Mule esb dataweaveMule esb dataweave
Mule esb dataweave
Rajkattamuri
 
Mule with drools
Mule with drools Mule with drools
Mule with drools
Rajkattamuri
 

More from Rajkattamuri (20)

Github plugin setup in anypointstudio
Github plugin setup in anypointstudioGithub plugin setup in anypointstudio
Github plugin setup in anypointstudio
 
For each component in mule
For each component in muleFor each component in mule
For each component in mule
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in mule
 
File component in mule
File component in muleFile component in mule
File component in mule
 
Database component in mule
Database component in muleDatabase component in mule
Database component in mule
 
Choice component in mule
Choice component in mule Choice component in mule
Choice component in mule
 
WebServices
WebServicesWebServices
WebServices
 
Java Basics in Mule
Java Basics in MuleJava Basics in Mule
Java Basics in Mule
 
WebServices Basic Overview
WebServices Basic OverviewWebServices Basic Overview
WebServices Basic Overview
 
Java For Begineers
Java For BegineersJava For Begineers
Java For Begineers
 
Java Basics
Java BasicsJava Basics
Java Basics
 
WebServices Basics
WebServices BasicsWebServices Basics
WebServices Basics
 
Core java
Core javaCore java
Core java
 
WebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDIWebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDI
 
Web services soap
Web services soapWeb services soap
Web services soap
 
Web services wsdl
Web services wsdlWeb services wsdl
Web services wsdl
 
Web services uddi
Web services uddiWeb services uddi
Web services uddi
 
Maven
MavenMaven
Maven
 
Mule esb dataweave
Mule esb dataweaveMule esb dataweave
Mule esb dataweave
 
Mule with drools
Mule with drools Mule with drools
Mule with drools
 

Recently uploaded

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 

Recently uploaded (20)

The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 

Exceptions in java

  • 2. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates error handling from main business logic Based on ideas developed in Ada, Eiffel and C++ Java has a uniform approach for handling all synchronous errors • From very unusual (e.g. out of memory) • To more common ones your program should check itself (e.g. index out of bounds) • From Java run-time system errors (e.g., divide by zero) • To errors that programmers detect and raise deliberately
  • 3. Throwing and catching An error can throw an exception throw <exception object>; By default, exceptions result in the thread terminating after printing an error message However, exception handlers can catch specified exceptions and recover from error catch (<exception type> e) { //statements that handle the exception }
  • 4. Throwing an exception • Example creates a subclass of Exception and throws an exception: class MyException extends Exception { } class MyClass { void oops() { if (/* no error occurred */) { /* normal processing */ } else { /* error occurred */ throw new MyException(); } } //oops }//class MyClass
  • 5. Exceptional flow of control Exceptions break the normal flow of control. When an exception occurs, the statement that would normally execute next is not executed. What happens instead depends on: ◦ whether the exception is caught, ◦ where it is caught, ◦ what statements are executed in the ‘catch block’, ◦ and whether you have a ‘finally block’.
  • 6. Approaches to handling an exception 1. Prevent the exception from happening 2. Catch it in the method in which it occurs, and either a. Fix up the problem and resume normal execution b. Rethrow it c. Throw a different exception 3. Declare that the method throws the exception 4. With 1. and 2.a. the caller never knows there was an error. 5. With 2.b., 2.c., and 3., if the caller does not handle the exception, the program will terminate and display a stack trace
  • 7. Exception hierarchy • Java organizes exceptions in inheritance tree: – Throwable – Error – Exception • RuntimeException • TooManyListenersException • IOException • AWTException
  • 8. Java is strict Unlike C++, is quite strict about catching exceptions If it is a checked exception ◦ (all except Error, RuntimeException and their subclasses), ◦ Java compiler forces the caller must either catch it ◦ or explicitly re-throw it with an exception specification. Why is this a good idea? By enforcing exception specifications from top to bottom, Java guarantees exception correctness at compile time. Here’s a method that ducks out of catching an exception by explicitly re-throwing it: void f() throws tooBig, tooSmall, divZero { ◦ The caller of this method now must either catch these exceptions or rethrow them in its specification.
  • 9. Error and RuntimeException Error ◦ “unchecked”, thus need not be in ‘throws’ clause ◦ Serious system problems (e.g. ThreadDeath, OutOfMemoryError) ◦ It’s very unlikely that the program will be able to recover, so generally you should NOT catch these. RuntimeException ◦ “unchecked”, thus need not be in ‘throws’ clause ◦ Also can occur almost anywhere, e.g. ArithmeticException, NullPointerException, IndexOutOfBoundsException ◦ Try to prevent them from happening in the first place! System will print stop program and print a trace
  • 10. Catching an exception try { // statement that could throw an exception } catch (<exception type> e) { // statements that handle the exception } catch (<exception type> e) { //e higher in hierarchy // statements that handle the exception } finally { // release resources } //other statements • At most one catch block executes • finally block always executes once, whether there’s an error or not
  • 11. Execution of try catch blocks • For normal execution: – try block executes, then finally block executes, then other statements execute • When an error is caught and the catch block throws an exception or returns: – try block is interrupted – catch block executes (until throw or return statement) – finally block executes • When error is caught and catch block doesn’t throw an exception or return: – try block is interrupted – catch block executes – finally block executes – other statements execute • When an error occurs that is not caught: – try block is interrupted – finally block executes
  • 12. Example: try { p.a = 10; } catch (NullPointerException e) { System.out.println("p was null"); } catch (Exception e) { System.out.println("other error occurred"); } catch (Object obj) { System.out.println("Who threw that object?"); } finally { System.out.println(“final processing"); } System.out.println(“Continue with more statements");
  • 13. Catch processing • When an exception occurs, the nested try/catch statements are searched for a catch parameter matching the exception class • A parameter is said to match the exception if it: – is the same class as the exception; or – is a superclass of the exception; or – if the parameter is an interface, the exception class implements the interface. • The first try/catch statement that has a parameter that matches the exception has its catch statement executed. • After the catch statement executes, execution resumes with the finally statement, then the statements after the try/catch statement.
  • 14. Catch processing example print("now");    try    { print("is ");         throw new MyException();        print("a ");    }  catch(MyException e)   { print("the ");   }    print("timen");  • Prints "now is the time". • Note that exceptions don't have to be used only for error handling • Would it be a good idea to exceptions for non-error processing? • But any other use is likely to result in code that's hard to understand.
  • 15. Declaring an exception type • Inherit from an existing exception type. • Provide a default constructor • and a constructor with one arg, type String. • Both should call super(astring); • Example: class MyThrowable extends Throwable {  // checked exception   MyThrowable () {      super ("Generated MyThrowable");   }   MyThrowable (String s) { super (s); } }
  • 16. Declaring an exception type • Inherit from an existing exception type. • Provide a default constructor • and a constructor with one arg, type String. • Both should call super(astring); class ErrorThrower { public void errorMethod() throws MyThrowable { throw new MyThrowable ("ErrorThrower"); // forces this method to declare MyThrowable } }
  • 17. Exceptions are ubiquitous in Java • Exception handling required for all read methods – Also many other system methods • If you use one of Java's built in class methods and it throws an exception, you must catch it (i.e., surround it in a try/catch block) or rethrow it, or you will get a compile time error: char ch; try { ch = (char) System.in.read(); } catch (IOException e) { System.err.println(e); return;