SlideShare a Scribd company logo
Java 104: Exceptions and
Errors in Java
Introduction
• Your Name: Manuela Grindei
• Your day job: Software Developer @ Gamesys
• Your last holiday destination: Vienna
Agenda
• Examples
• Class Hierarchy
• try-catch-finally blocks
• multi-catch and try-with-resources
• Exception propagation
• Checked vs unchecked exceptions
• Custom exceptions
Example 1
What will be the outcome of the following program and why?
int[] a = {1,2,3,4,5};
for (int i = 1; i <= 5 ; i++) {
System.out.println(a[i]);
}
System.out.println(“Finished”);
Example 1
What will be the outcome of the following program and why?
int[] a = {1,2,3,4,5};
for (int i = 1; i <= 5 ; i++) {
System.out.println(a[i]);
}
System.out.println(“Finished”);
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5
Example 2
What will be the outcome of the following program and why?
static String s;
public static void main(String[] args) {
System.out.println(s.length());
}
Example 2
What will be the outcome of the following program and why?
static String s;
public static void main(String[] args) {
System.out.println(s.length());
}
Exception in thread "main" java.lang.NullPointerException
Example 3
What will be the outcome of the following program and why?
Integer i = 2;
Long l = (Long)(Number) i;
System.out.println(l);
Example 3
What will be the outcome of the following program and why?
Integer i = 2;
Long l = (Long)(Number) i;
System.out.println(l);
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer
cannot be cast to java.lang.Long
Example 4
Fibonacci Numbers
Fib0 = 1
Fib1 = 1
Fibn = Fibn-1 + Fibn-2
long fib(long i) {
if (i == 0) {
return 1;
}
if (i == 1) {
return 1;
} else {
return fib(i - 1) + fib(i - 2);
}
}
fib(3) = ?
fib(100_000) = ?
Example 4
Fibonacci Numbers
Fib0 = 1
Fib1 = 1
Fibn = Fibn-1 + Fibn-2
long fib(long i) {
if (i == 0) {
return 1;
}
if (i == 1) {
return 1;
} else {
return fib(i - 1) + fib(i - 2);
}
}
fib(3) – returns correct answer
fib(100_000) - StackOverflowError
Class Hierarchy
serious problems
that a reasonable
application should
not try to catch
Checked
exceptions
Unchecked
exceptions
conditions that a reasonable
application might want to catch
Exceptions in Java 8
Runtime Exceptions is Java 8
Errors in Java 8
Exceptions
• Exceptions are thrown by a program, and may be caught and handled by
another part of the program
• A program can have a normal execution flow and an exception execution
flow
• Java has a predefined set of exceptions and errors that can occur during
execution
• A program can deal with an exception by:
• ignoring it (see first examples)
• handling it where it occurs
• handling it in another place in the program
try-catch
try {
//guarded region, i.e. code that might throw exceptions
…
} catch (Exception1 e1) {
//Exception1 handler
…
} catch (Exception2 e2) {
//Exception2 handler
…
}
- If an exception occurs in try block, the control will
get transferred to the appropriate catch handler
- A catch handler shows that we know how to handle
exceptions of that type
- If Exception1 is a subclass of Exception2, its catch
block should come first (start with the most specific
exception)
Exception swallowing
Do NOT write catch handlers like this:
catch(Exception e) {}
- program continues processing as if nothing had gone wrong
- the ignored exception may lead the application to an unexpected failure
- code can be hard to debug
- if the exception really needs to be caught, log some information about it!
Example
File file = new File("file.txt");
Writer writer = null;
try {
writer = new PrintWriter(file);
writer.write(new BigDecimal("Hello world!").toString());
writer.flush();
writer.close();
} catch(FileNotFoundException e) {
System.out.println("Caught " + e.getClass().getName());
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
} catch (NumberFormatException e) {
System.out.println("Caught " + e.getClass().getName());
}
What is wrong with the above code?
Example
File file = new File("file.txt");
Writer writer = null;
try {
writer = new PrintWriter(file);
writer.write(new BigDecimal("Hello world!").toString());
writer.flush();
writer.close();
} catch(FileNotFoundException e) {
System.out.println("Caught " + e.getClass().getName());
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
} catch (NumberFormatException e) {
System.out.println("Caught " + e.getClass().getName());
}
Is the file always closed?
Fix
File file = new File("file.txt");
Writer writer = null;
try {
writer = new PrintWriter(file);
writer.write(new BigDecimal("Hello world!").toString());
writer.flush();
}
catch (NumberFormatException e) {
System.out.println("Caught " + e.getClass().getName());
}
catch(FileNotFoundException e) {
System.out.println("Caught " + e.getClass().getName());
}
catch (IOException e) {
System.out.println("Caught IOException "+ e.getMessage());
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException e) {
System.err.println("Caught IOException");
}
}
Finally block
• any try block needs to be followed by at least a catch or finally block
• finally block always gets executed (unless JVM exits while the try/catch is
being executed or the thread executing the try/catch is interrupted or
killed)
• if there is a return statement in the try block, the finally block executes
right after the return statement is encountered, and before the return
executes
• if an exception is thrown, finally block executes immediately after the
corresponding catch block completes
• if there is no exception, finally executes immediately after the try block
• finally is the ideal place to release resources
Multi-catch
File file = new File("file.txt");
Writer writer = null;
try {
writer = new PrintWriter(file);
writer.write(new BigDecimal("Hello world!").toString());
writer.flush();
}
catch (NumberFormatException | IOException e) {
//e is final
//the exceptions must be in different inheritance hierarchies
System.out.println("Caught " + e.getClass().getName());
} finally {
if (writer != null)
try {
writer.close();
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
}
try-with-resources
public static void main(String[] args) throws IOException {
File file = new File("file.txt");
try(Writer writer = new PrintWriter(file)) {
writer.write(new BigDecimal("Hello world!").toString());
writer.flush();
}
}
- Code is more concise and readable
- Automatic Resource Management closes the file for us
- The resources are declared in try between () and must implement AutoCloseable
throw/throws
• A method can throw a new exception:
throw new Exception();
throw new IllegalArgumentException();
• A method can specify in its declaration that it throws one or more exceptions
void f() throws Exception1, Exception2;
void f() throws Exception1, Exception2{//…}
Exception propagation
public static void main(String[] args) {
doStuff();
}
private static void doStuff() {
doMoreStuff();
}
private static void doMoreStuff() {
int x = 5/0;
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Exercise.doMoreStuff(Exercise.java:10)
at Exercise.doStuff(Exercise.java:7)
at Exercise.main(Exercise.java:4)
Checked vs unchecked exceptions
Checked Exceptions Unchecked Exceptions
Checked by the compiler Unchecked by the compiler
Extend Exception Extend RuntimeException
If a method throws them, they need to be specified in
that method’s declaration
If a method throws them, they can be specified in the
declaration, but it’s not mandatory
They need to either be caught or rethrown explicitly
by a method
No restrictions
Show recoverable conditions Show programming errors
Custom Exceptions
• We can create our own business exceptions by extending either
Exception or RuntimeException
• We can use our exceptions just like the standard ones
Example - PersonValidator
public class Person {
private String name;
private int age;
public Person() {}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//getters and setters
}
public class PersonValidationException extends RuntimeException {
public PersonValidationException(String s) {
super(s);
}
}
}
Example - PersonValidator
public final class PersonValidator {
public static final int MAX_LENGTH = 60;
private PersonValidator(){}
public static void validate(Person p) {
if (p.getName() == null || p.getName().isEmpty()) {
throw new PersonValidationException("The person must have a name");
}
if (p.getName().length() > MAX_LENGTH) {
throw new PersonValidationException("The name cannot be longer than "
+ MAX_LENGTH + " characters");
}
if (p.getAge() < 18) {
throw new PersonValidationException("The person cannot be underage");
}
}
}
Example - PersonValidator
public static void main(String[] args) {
Person validPerson = new Person("John", 25);
PersonValidator.validate(validPerson);
Person personWithInvalidAge = new Person("Tom", 17);
PersonValidator.validate(personWithInvalidAge);
}
Benefits of exception handling
• detect errors easily without writing additional code to test return
values
• exception-handling code is clearly separated from exception-
generating code
• the same exception-handling code can deal with several possible
exceptions
• code to handle an exception that may occur in the governed region
needs to be written only once
Conclusions
• Do NOT swallow exceptions
• Use checked exceptions for conditions from which the caller can
reasonably be expected to recover
the exceptional condition cannot be prevented by proper use of the API
the programmer using the API can take some useful action once confronted
with the exception
• Use runtime exceptions to indicate programming errors (mostly
precondition violations)
• By convention: errors are reserved for use by the JVM to indicate
resource deficiencies, invariant failures etc. – do NOT subclass Error

More Related Content

What's hot

Object Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypassObject Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypass
Sam Thomas
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
Naresh Chintalcheru
 
02 Java Language And OOP Part II LAB
02 Java Language And OOP Part II LAB02 Java Language And OOP Part II LAB
02 Java Language And OOP Part II LAB
Hari Christian
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
Ganesh Samarthyam
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
Ganesh Samarthyam
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
Ganesh Samarthyam
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
Iram Ramrajkar
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
Nishan Barot
 
OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertions
Hari kiran G
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
Niraj Bharambe
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
Niraj Bharambe
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
Ganesh Samarthyam
 
01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB
Hari Christian
 
Next Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized TestingNext Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized Testing
Tao Xie
 

What's hot (20)

Object Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypassObject Oriented Exploitation: New techniques in Windows mitigation bypass
Object Oriented Exploitation: New techniques in Windows mitigation bypass
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
02 Java Language And OOP Part II LAB
02 Java Language And OOP Part II LAB02 Java Language And OOP Part II LAB
02 Java Language And OOP Part II LAB
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertions
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB01 Java Language And OOP Part I LAB
01 Java Language And OOP Part I LAB
 
Next Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized TestingNext Generation Developer Testing: Parameterized Testing
Next Generation Developer Testing: Parameterized Testing
 

Similar to Java 104

Lab4
Lab4Lab4
Exception handling
Exception handlingException handling
Exception handling
Sandeep Rawat
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta Language
ESUG
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
Mahmoud Ouf
 
Exception handling
Exception handlingException handling
Exception handling
SAIFUR RAHMAN
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch
 
Java practical
Java practicalJava practical
Java practical
william otto
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
Rafael Winterhalter
 
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.ppt
 Exception Handling.ppt Exception Handling.ppt
Exception Handling.ppt
Faisaliqbal203156
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
cbeproject centercoimbatore
 
Server1
Server1Server1
Server1
FahriIrawan3
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 

Similar to Java 104 (20)

Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Lab4
Lab4Lab4
Lab4
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Application-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta LanguageApplication-Specific Models and Pointcuts using a Logic Meta Language
Application-Specific Models and Pointcuts using a Logic Meta Language
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Inheritance
InheritanceInheritance
Inheritance
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Exception handling
Exception handlingException handling
Exception handling
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Java practical
Java practicalJava practical
Java practical
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
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
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exception Handling.ppt
 Exception Handling.ppt Exception Handling.ppt
Exception Handling.ppt
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
Server1
Server1Server1
Server1
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 

Recently uploaded

A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
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
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
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
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
KrzysztofKkol1
 
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
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
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
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
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
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
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
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 

Recently uploaded (20)

A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
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...
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
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
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
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
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
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...
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
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
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
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
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 

Java 104

  • 1. Java 104: Exceptions and Errors in Java
  • 2. Introduction • Your Name: Manuela Grindei • Your day job: Software Developer @ Gamesys • Your last holiday destination: Vienna
  • 3. Agenda • Examples • Class Hierarchy • try-catch-finally blocks • multi-catch and try-with-resources • Exception propagation • Checked vs unchecked exceptions • Custom exceptions
  • 4. Example 1 What will be the outcome of the following program and why? int[] a = {1,2,3,4,5}; for (int i = 1; i <= 5 ; i++) { System.out.println(a[i]); } System.out.println(“Finished”);
  • 5. Example 1 What will be the outcome of the following program and why? int[] a = {1,2,3,4,5}; for (int i = 1; i <= 5 ; i++) { System.out.println(a[i]); } System.out.println(“Finished”); Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
  • 6. Example 2 What will be the outcome of the following program and why? static String s; public static void main(String[] args) { System.out.println(s.length()); }
  • 7. Example 2 What will be the outcome of the following program and why? static String s; public static void main(String[] args) { System.out.println(s.length()); } Exception in thread "main" java.lang.NullPointerException
  • 8. Example 3 What will be the outcome of the following program and why? Integer i = 2; Long l = (Long)(Number) i; System.out.println(l);
  • 9. Example 3 What will be the outcome of the following program and why? Integer i = 2; Long l = (Long)(Number) i; System.out.println(l); Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
  • 10. Example 4 Fibonacci Numbers Fib0 = 1 Fib1 = 1 Fibn = Fibn-1 + Fibn-2 long fib(long i) { if (i == 0) { return 1; } if (i == 1) { return 1; } else { return fib(i - 1) + fib(i - 2); } } fib(3) = ? fib(100_000) = ?
  • 11. Example 4 Fibonacci Numbers Fib0 = 1 Fib1 = 1 Fibn = Fibn-1 + Fibn-2 long fib(long i) { if (i == 0) { return 1; } if (i == 1) { return 1; } else { return fib(i - 1) + fib(i - 2); } } fib(3) – returns correct answer fib(100_000) - StackOverflowError
  • 12. Class Hierarchy serious problems that a reasonable application should not try to catch Checked exceptions Unchecked exceptions conditions that a reasonable application might want to catch
  • 16. Exceptions • Exceptions are thrown by a program, and may be caught and handled by another part of the program • A program can have a normal execution flow and an exception execution flow • Java has a predefined set of exceptions and errors that can occur during execution • A program can deal with an exception by: • ignoring it (see first examples) • handling it where it occurs • handling it in another place in the program
  • 17. try-catch try { //guarded region, i.e. code that might throw exceptions … } catch (Exception1 e1) { //Exception1 handler … } catch (Exception2 e2) { //Exception2 handler … } - If an exception occurs in try block, the control will get transferred to the appropriate catch handler - A catch handler shows that we know how to handle exceptions of that type - If Exception1 is a subclass of Exception2, its catch block should come first (start with the most specific exception)
  • 18. Exception swallowing Do NOT write catch handlers like this: catch(Exception e) {} - program continues processing as if nothing had gone wrong - the ignored exception may lead the application to an unexpected failure - code can be hard to debug - if the exception really needs to be caught, log some information about it!
  • 19. Example File file = new File("file.txt"); Writer writer = null; try { writer = new PrintWriter(file); writer.write(new BigDecimal("Hello world!").toString()); writer.flush(); writer.close(); } catch(FileNotFoundException e) { System.out.println("Caught " + e.getClass().getName()); } catch (IOException e) { System.out.println("Caught IOException: " + e.getMessage()); } catch (NumberFormatException e) { System.out.println("Caught " + e.getClass().getName()); } What is wrong with the above code?
  • 20. Example File file = new File("file.txt"); Writer writer = null; try { writer = new PrintWriter(file); writer.write(new BigDecimal("Hello world!").toString()); writer.flush(); writer.close(); } catch(FileNotFoundException e) { System.out.println("Caught " + e.getClass().getName()); } catch (IOException e) { System.out.println("Caught IOException: " + e.getMessage()); } catch (NumberFormatException e) { System.out.println("Caught " + e.getClass().getName()); } Is the file always closed?
  • 21. Fix File file = new File("file.txt"); Writer writer = null; try { writer = new PrintWriter(file); writer.write(new BigDecimal("Hello world!").toString()); writer.flush(); } catch (NumberFormatException e) { System.out.println("Caught " + e.getClass().getName()); } catch(FileNotFoundException e) { System.out.println("Caught " + e.getClass().getName()); } catch (IOException e) { System.out.println("Caught IOException "+ e.getMessage()); } finally { if (writer != null) try { writer.close(); } catch (IOException e) { System.err.println("Caught IOException"); } }
  • 22. Finally block • any try block needs to be followed by at least a catch or finally block • finally block always gets executed (unless JVM exits while the try/catch is being executed or the thread executing the try/catch is interrupted or killed) • if there is a return statement in the try block, the finally block executes right after the return statement is encountered, and before the return executes • if an exception is thrown, finally block executes immediately after the corresponding catch block completes • if there is no exception, finally executes immediately after the try block • finally is the ideal place to release resources
  • 23. Multi-catch File file = new File("file.txt"); Writer writer = null; try { writer = new PrintWriter(file); writer.write(new BigDecimal("Hello world!").toString()); writer.flush(); } catch (NumberFormatException | IOException e) { //e is final //the exceptions must be in different inheritance hierarchies System.out.println("Caught " + e.getClass().getName()); } finally { if (writer != null) try { writer.close(); } catch (IOException e) { System.out.println("Caught IOException: " + e.getMessage()); } }
  • 24. try-with-resources public static void main(String[] args) throws IOException { File file = new File("file.txt"); try(Writer writer = new PrintWriter(file)) { writer.write(new BigDecimal("Hello world!").toString()); writer.flush(); } } - Code is more concise and readable - Automatic Resource Management closes the file for us - The resources are declared in try between () and must implement AutoCloseable
  • 25. throw/throws • A method can throw a new exception: throw new Exception(); throw new IllegalArgumentException(); • A method can specify in its declaration that it throws one or more exceptions void f() throws Exception1, Exception2; void f() throws Exception1, Exception2{//…}
  • 26. Exception propagation public static void main(String[] args) { doStuff(); } private static void doStuff() { doMoreStuff(); } private static void doMoreStuff() { int x = 5/0; } Exception in thread "main" java.lang.ArithmeticException: / by zero at Exercise.doMoreStuff(Exercise.java:10) at Exercise.doStuff(Exercise.java:7) at Exercise.main(Exercise.java:4)
  • 27. Checked vs unchecked exceptions Checked Exceptions Unchecked Exceptions Checked by the compiler Unchecked by the compiler Extend Exception Extend RuntimeException If a method throws them, they need to be specified in that method’s declaration If a method throws them, they can be specified in the declaration, but it’s not mandatory They need to either be caught or rethrown explicitly by a method No restrictions Show recoverable conditions Show programming errors
  • 28. Custom Exceptions • We can create our own business exceptions by extending either Exception or RuntimeException • We can use our exceptions just like the standard ones
  • 29. Example - PersonValidator public class Person { private String name; private int age; public Person() {} public Person(String name, int age) { this.name = name; this.age = age; } //getters and setters } public class PersonValidationException extends RuntimeException { public PersonValidationException(String s) { super(s); } } }
  • 30. Example - PersonValidator public final class PersonValidator { public static final int MAX_LENGTH = 60; private PersonValidator(){} public static void validate(Person p) { if (p.getName() == null || p.getName().isEmpty()) { throw new PersonValidationException("The person must have a name"); } if (p.getName().length() > MAX_LENGTH) { throw new PersonValidationException("The name cannot be longer than " + MAX_LENGTH + " characters"); } if (p.getAge() < 18) { throw new PersonValidationException("The person cannot be underage"); } } }
  • 31. Example - PersonValidator public static void main(String[] args) { Person validPerson = new Person("John", 25); PersonValidator.validate(validPerson); Person personWithInvalidAge = new Person("Tom", 17); PersonValidator.validate(personWithInvalidAge); }
  • 32. Benefits of exception handling • detect errors easily without writing additional code to test return values • exception-handling code is clearly separated from exception- generating code • the same exception-handling code can deal with several possible exceptions • code to handle an exception that may occur in the governed region needs to be written only once
  • 33. Conclusions • Do NOT swallow exceptions • Use checked exceptions for conditions from which the caller can reasonably be expected to recover the exceptional condition cannot be prevented by proper use of the API the programmer using the API can take some useful action once confronted with the exception • Use runtime exceptions to indicate programming errors (mostly precondition violations) • By convention: errors are reserved for use by the JVM to indicate resource deficiencies, invariant failures etc. – do NOT subclass Error