SlideShare ist ein Scribd-Unternehmen logo
1 von 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();
}

Weitere ähnliche Inhalte

Ähnlich wie 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
 

Kürzlich hochgeladen

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

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...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

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