SlideShare una empresa de Scribd logo
1 de 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();
}

Más contenido relacionado

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

Último

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 

Último (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

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(); }