• java.lang.NullPointerException and RuntimeException should not be caught by the programs
  • A NullPointerException indicates about the existence of null pointer dereference by throwing an exception at runtime
  • Bugs in the program are indicated by the Runtime exceptions need to be fixed by the programmer

Vulnerable Code

  • The following code gives an example based on isName() method
  • In this method a String argument is taken and if the given string is a valid name then it returns true
  • When this method fails to check whether the given string is null or not and instead catches NullPointerException, then it returns false

Secure Code

  • The following code checks if the given string is null or not instead of catching the NullPointerException

Erroneous Exceptional Behaviors: Never Allow Methods to Throw RuntimeException, Exception, or Throwable

  • RuntimeException, Exception, or Throwable should not be thrown or else it may lead to various errors

Vulnerable Code

  • The following code uses toUpperCase() method
  • This method accepts a string and returns true if the string is a capital letter followed by lowercase letters
  • When a null string argument is passed this method throws a RuntimeException

Secure Code

  • The following code throws a NullPointerException in order to denote exceptional condition

Erroneous Exceptional Behaviors: Never Throw Undeclared Checked Exceptions

  1. In Java, there are a few techniques that permit throwing the undeclared checked exceptions at runtime
  2. These techniques do not allow the usage of throws clause by weakening the ability of caller methods
  3. These techniques should never be used to throw undeclared checked exceptions

Vulnerable Code

  • The given vulnerable code throws undeclared checked exceptions
  • This code uses the undelcaredThrow() method that takes a Throwable argument and then invokes a function that throws the argument without declaration

Secure Code

  • This solution code uses java.lang.reflect.Constructor.newlnstance() instead of Class.newInstance()
  • The Constructor.newInstance() process shawls any exceptions thrown from within the constructor into a checked exception known as Invocation Target Exception

Erroneous Exceptional Behaviors: Never Let Checked Exceptions Escape from Finally Block

  • Methods invoked from within a finally block throw an exception
  • If such exceptions are not caught and handled then it results in termination of entire try block

Vulnerable Code

  • This vulnerable code has a finally block which closes reader object
  • It is wrongly assumed by the programmer that the statements of the finally block do not throw exceptions
  • This results in the failure of handling exceptions

Secure Code

  • The code enfolds the close() method request in a try-catch block in the finally block
  • Therefore, the potential IOException is held without allowing it to circulate anymore