3. Encapsulation
– In a scenario where a function throws an exception that is received from another function, it should be encapsulated in a locally generated exception class
– In the sample code, FileNotFoundException is converted into ActionException
– When the code encounters the FileNotFoundException inside the try block, the catch clause throws an ActionException
– The execution thread is suspended and the exception is reported. The function getCause() can be made use of to find the root exception cause
Example

Best Practices for Handling Exceptions in Java (Cont’d)
4. Balance the catch blocks
– There are two approaches that can be used to balance the catch blocks:
The first approach is to use a single catch block for all the events.
- This approach is not a good practice as it does not give control over the exceptions being caught

The second approach is to use multiple catch blocks .i.e., each exception will have a separate catch block
For example: Many catch blocks one for each Exception

- Developers should follow this approach as it is easy to execute various operations depending on the exceptions thrown
Best Practices for Handling Exceptions in Java (Cont’d)
5. Create custom error pages
– A generic error page should be used for all exceptions
– This prevents an attacker from retrieving internal response to errors
This can be done using the following ways:
- Declarative Exception Handling using Struts
– The code should be included in struts-config.xml

2. Using Java Servlets
– The code should be implemented in web.xml

Best Practices for Handling Exceptions in Java (Cont’d)
6. Exception names should be meaningful
– The exception names must be meaningful and should express the action that caused them
– Programmers should make sure to use specific exceptions and not generic exceptions
– Example: java.io.FileNotFoundException can be used as it implies that file is not found
– java.lang.Exception should not be used as it is very generic
7. Throw early and catch late
– This principle should be followed by all programmers
– The exception should be thrown early and caught late