SlideShare a Scribd company logo
1 of 8
Lightning Talk on Java
Common Programming
Oversights
Chetan Narsude
January 20th, 2014
Don’t Swallow Exceptions
• Mistake
try {
}
catch (Exception e) {
e.printStackTrace();
}

• Bad
try {
}
catch (Exception e) {
logger.warn(“Exception”, e);
}

Recommended
try {
}
catch (Throwable e) {
if (e instanceof Error) {
throw (Error)e;
}
if (e instanceof RuntimeException) {
throw (Runtime)e;
}

• Ugly
try {
}
catch (Exception e) {
handleException(e);
}
/* somewhere else */
public void handleException(Exception e){}

throw new RuntimeException(e);
}
Don’t wrap Throwable in
RuntimeException
try {

try {
…

…

}

}

catch (Throwable cause) {

catch (Throwable cause) {

throw new RuntimeException(cause);
}

DTThrowable.rethrow(cause);
}
Don’t Catch All Throwable
try {

try {
…

…

}

}

catch (Throwable cause) {

catch (Error error) {

throw new RuntimeException(cause);
}

throw error;
}
catch (RuntimeException runtime) {
throw runtime;
}
catch (Throwable cause) {
throw new Runtime(cause);
}
Don’t Use Static Instance of
SimpleDateFormat
private static final DateFormat dateFormat
= new SimpleDateFormat("yyyy-MM-dd");
…
/* somewhere in the code */
ed =
dateFormat.parse(dateInput.readUTF());

…
/* somewhere in the code */
ed = new SimpleDateFormat("yyyy-MMdd").parse(dateInput.readUTF());

private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>()
{
@Override
protected DateFormat initialValue()
{
return new SimpleDateFormat(“yyyy-MM-dd”);
}
}
…
/* somewhere in the code */
ed = dateFormat.get().parse(dateInput.readUTF());
Synchronize Only on Final
private Object mutex = new Object();

private final Object mutex = new Object();

/* somewhere in the code */
synchronized (mutex) {
reload = true;
mutex.notify();
}

/* somewhere in the code */
synchronized (mutex) {
reload = true;
mutex.notify();
}

/* possibly elsewhere in the code */
public void setMutex(Object mutex)
{
this.mutex = mutex;
}
Avoid Concatenation While Logging
/* various ways of wrongly using logger */
logger.debug(“Exception = “ + e.getMessage());
logger.debug(“Exception = {}”, e);
logger.debug(“Exception “ + id + “ “ + e.toString());

/* just print the message from exception */
logger.debug(“Exception = {}“, e.getMessage());
/* print the exception stack trace */
logger.debug(“Some Operation”, e);
/* print templatized message with exception stack trace */
logger.debug(“Exception {}“, id, e);
Prevent Resource Leak
InputStream stream = new …Stream();

InputStream stream = new …Stream();

while (…) {

try {

process(stream);

while (…) {

}

process(stream);

stream.close();

}
}
finally {
stream.close();
}

More Related Content

Similar to Lightning talk on java

Exceptions in PHP
Exceptions in PHPExceptions in PHP
Exceptions in PHPJanTvrdik
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
exceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptxexceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptxARUNPRANESHS
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладкаDEVTYPE
 
Better Strategies for Null Handling in Java
Better Strategies for Null Handling in JavaBetter Strategies for Null Handling in Java
Better Strategies for Null Handling in JavaStephan Schmidt
 
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 developmentrohitgudasi18
 
Java_Exception-CheatSheet_Edureka.pdf
Java_Exception-CheatSheet_Edureka.pdfJava_Exception-CheatSheet_Edureka.pdf
Java_Exception-CheatSheet_Edureka.pdfFurkan Furkan
 
About java
About javaAbout java
About javaJay Xu
 

Similar to Lightning talk on java (10)

Exceptions in PHP
Exceptions in PHPExceptions in PHP
Exceptions in PHP
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
exceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptxexceptionhandlinginjava-140224181412-phpapp02.pptx
exceptionhandlinginjava-140224181412-phpapp02.pptx
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
Exception handling
Exception handlingException handling
Exception handling
 
Better Strategies for Null Handling in Java
Better Strategies for Null Handling in JavaBetter Strategies for Null Handling in Java
Better Strategies for Null Handling in Java
 
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
 
Java_Exception-CheatSheet_Edureka.pdf
Java_Exception-CheatSheet_Edureka.pdfJava_Exception-CheatSheet_Edureka.pdf
Java_Exception-CheatSheet_Edureka.pdf
 
About java
About javaAbout java
About java
 

Recently uploaded

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 

Recently uploaded (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

Lightning talk on java

  • 1. Lightning Talk on Java Common Programming Oversights Chetan Narsude January 20th, 2014
  • 2. Don’t Swallow Exceptions • Mistake try { } catch (Exception e) { e.printStackTrace(); } • Bad try { } catch (Exception e) { logger.warn(“Exception”, e); } Recommended try { } catch (Throwable e) { if (e instanceof Error) { throw (Error)e; } if (e instanceof RuntimeException) { throw (Runtime)e; } • Ugly try { } catch (Exception e) { handleException(e); } /* somewhere else */ public void handleException(Exception e){} throw new RuntimeException(e); }
  • 3. Don’t wrap Throwable in RuntimeException try { try { … … } } catch (Throwable cause) { catch (Throwable cause) { throw new RuntimeException(cause); } DTThrowable.rethrow(cause); }
  • 4. Don’t Catch All Throwable try { try { … … } } catch (Throwable cause) { catch (Error error) { throw new RuntimeException(cause); } throw error; } catch (RuntimeException runtime) { throw runtime; } catch (Throwable cause) { throw new Runtime(cause); }
  • 5. Don’t Use Static Instance of SimpleDateFormat private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); … /* somewhere in the code */ ed = dateFormat.parse(dateInput.readUTF()); … /* somewhere in the code */ ed = new SimpleDateFormat("yyyy-MMdd").parse(dateInput.readUTF()); private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat(“yyyy-MM-dd”); } } … /* somewhere in the code */ ed = dateFormat.get().parse(dateInput.readUTF());
  • 6. Synchronize Only on Final private Object mutex = new Object(); private final Object mutex = new Object(); /* somewhere in the code */ synchronized (mutex) { reload = true; mutex.notify(); } /* somewhere in the code */ synchronized (mutex) { reload = true; mutex.notify(); } /* possibly elsewhere in the code */ public void setMutex(Object mutex) { this.mutex = mutex; }
  • 7. Avoid Concatenation While Logging /* various ways of wrongly using logger */ logger.debug(“Exception = “ + e.getMessage()); logger.debug(“Exception = {}”, e); logger.debug(“Exception “ + id + “ “ + e.toString()); /* just print the message from exception */ logger.debug(“Exception = {}“, e.getMessage()); /* print the exception stack trace */ logger.debug(“Some Operation”, e); /* print templatized message with exception stack trace */ logger.debug(“Exception {}“, id, e);
  • 8. Prevent Resource Leak InputStream stream = new …Stream(); InputStream stream = new …Stream(); while (…) { try { process(stream); while (…) { } process(stream); stream.close(); } } finally { stream.close(); }