Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views5 pages

Week6 Exception Handling

This chapter covers the importance of proper exception handling in web applications to prevent information leakage that could be exploited by attackers. It explains the types of exceptions in Java, including checked and unchecked exceptions, and provides examples of handling exceptions using try-catch-finally blocks and Spring MVC annotations. The document also includes code examples for handling exceptions at the controller level and creating custom error pages.

Uploaded by

begogo6798
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views5 pages

Week6 Exception Handling

This chapter covers the importance of proper exception handling in web applications to prevent information leakage that could be exploited by attackers. It explains the types of exceptions in Java, including checked and unchecked exceptions, and provides examples of handling exceptions using try-catch-finally blocks and Spring MVC annotations. The document also includes code examples for handling exceptions at the controller level and creating custom error pages.

Uploaded by

begogo6798
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Exception Handling

Notes

Goal of the chapter

In this chapter you will learn about how improper error handling can
reveal information about the internal workings of the web application.
You will also learn how to correctly handle errors and also log them in a
manner that can be accessed by the administrators for troubleshooting

1 Exceptions and errors in your web application


Errors and exceptions in your web applications may happen due to irrecoverable
conditions such as memory leak, Linkage-Error, or any an unexpected during
the execution of the application. Exceptions and errors provide information to
the application developers what went wrong and ways to fix those. However,
this could also provide useful information for the attacker. Attackers can use
the leaked information achieved from error messages to perform attacks. Appli-
cation developers need to ensure that exceptions are dealt with a way so that
they don’t disclose useful information to the attackers
All exceptions and errors in Java language goes back to the parent class
Throwable. They are mainly two types checked (compile time) exceptions and
unchecked (runtime) exceptions. Compile time exceptions belong to the base
class ‘Exception’ and can be fixed during development of the apps. Runtime
exceptions belong to the base class ‘RuntimeException’. They may occur during
the execution of the applications and can expose useful information to the user.
Errors are exceptional conditions that are typically caused by the system
itself, e.g. lack of resources. These are usually beyond the control of the ap-
plication. They represent serious problems that may prevent the application
from running. They are not meant to be caught or handled. Examples of errors
include OutOfMemoryError, StackOverflowError, LinkageError and Assertion-
Error etc. Figure 1 shows the hierarchy of exceptions and errors in Java.

1
Figure 1: The hierarchy of exceptions and errors

1 try {
2 // Code that may throw an exception
3 int divResult = divide (100 , 0) ;
4 System . out . println ( " Result of teh division : " + divResult ) ;
5 } catch ( A r i t h m e t i c E x c e p t i o n ex ) {
6 // Exception handling
7 System . out . println ( " An exception occurred : " + ex .
8 getMessage () ) ;
9
10 } finally {
11 // Finally block
12 System . out . println ( " This block is always executed . " ) ;
13 }
14 // Method that throws an exception
15
16 public int divide ( int dividend , int divisor ) {
17 return dividend / divisor ;
18 }

Code-1: Example of Exception

In the above example Code-1, the divide() method throws an ‘ArithmeticEx-


ception’ when the divisor is zero. This exception is handled using a try-catch-
finally block. The exception is caught and handled in the catch block. The
finally block is executed regardless of whether an exception occurred or not.

2 Handling exceptions and errors in Spring MVC


Spring MVC provides several mechanisms to handle exceptions and customise
the error handling process including Controller Level Exception Handler, Global
Exception Handler. Controller exception can be handled by adding @Exception-
Handler annotation. The Global Exception Handler can be handled by adding

2
@ControllerAdvice annotation. Using @ExceptionHandler: You can use the
@ExceptionHandler annotation at the controller level or the specific handler
method level to handle exceptions. By annotating a method with @Exception-
Handler and specifying the exception type, you can define how to handle that
particular exception. When the exception occurs, Spring MVC invokes the cor-
responding handler method to handle the exception. Let’s see an example of
Controller level exception handler. Complete code needs to be seen in the VM’s
project supplied.

3
1 package edu . deakin . sit218 . coachwebapp ;
2 import org . s pr i ng fr am e wo rk . web . bind . annotation . ModelA ttribute ;
3 import org . s pr i ng fr am e wo rk . web . bind . annotation . Reques tMapping ;
4 import org . s pr i ng fr am e wo rk . web . bind . annotation . E xc e p t i o n H a n d l e r ;
5 import java . util . logging .*;
6
7 @Controller
8 @ Re qu es t Ma pp in g ( " / workout " )
9 public class C oa ch Co n tr ol l er {
10 static Logger logger = Logger . getLogger ( C o ac hC o nt ro ll e r . class .
getName () ) ;
11
12
13 @ Re qu e st Ma pp i ng ( " / processForm " )
14 public String workout (
15 @Valid @ Mo d el At t ri bu te ( " client " ) Client client ,
16 BindingResult validationErrors , Model model ) {
17 // Input validation
18 if ( v a l i d a t i o n E r r o r s . hasErrors () )
19 return " client - form " ;
20 // throw new I l l e g a l A r g u m e n t E x c e p t i o n (" Invalid Input ") ;
21 // Logic when there is no error
22
23
24 if ( client . getName () . equals ( " Rolando " ) ) {
25 model . addAttribute ( " message " , " Rolando never workouts " ) ;
26 }
27 else if ( client . age < 40) {
28 model . addAttribute ( " message " , " Hey , " + client . getName () +
29 " you are still too young , no need to work out ! " ) ;
30 }
31 else {
32 model . addAttribute ( " message " , client . getName () +
33 " , please , run for 30 min " ) ;
34 }
35 return " workout " ;
36
37 }
38
39 @ E x c e p t i o n H a n d l e r ( N u l l P o i n t e r E x c e p t i o n . class )
40 public String errorHandler ( Model theModel , N u l l P o i n t e r E x c e p t i o n ex )
41 {
42 theModel . addAttribute ( " err " ," something went wrong " ) ;
43 logger . log ( Level . WARNING , ex . toString () ) ;
44
45 return " error " ;
46 }
47
48
49 @ E x c e p t i o n H a n d l e r ( N u l l P o i n t e r E x c e p t i o n . class )
50 public String errorHandler ( Model theModel , N u l l P o i n t e r E x c e p t i o n ex )
51 {
52 theModel . addAttribute ( " err " ," something went wrong " ) ;
53 logger . log ( Level . WARNING , ex . toString () ) ;
54
55 return " error " ;
56 }
57
58
59 /*
60 @ E x c e p t i o n H a n d l e r ( N u l l P o i n t e r E x c e p t i o n . class , A r i t h m e t i c E x c e p t i o n
. class )
61 public String errorHandler ( Model theModel , Exception ex )
62 {
63 theModel . addAttribute (" err " ," something went wrong ") ;
64 logger . log ( Level . WARNING , ex . toString () ) ;
65
66 return " error ";
67 }
68
69 */ 4
70
71
72 }

Code-2: Example of Exception Handler


In the Code-2: @ExceptionHandler(NullPointerException.class) is added be-
fore the handler method public String errorHandler(Model theModel, NullPoint-
erException ex) which will handle the NullPointerException. You may handle
multiple exceptions using the same handler as @ExceptionHandler(NullPointerException.class,
ArithmeticException.class) . In the Code-2, when exception happens, public
String errorHandler(Model theModel, NullPointerException ex) will be called
which returns the error.jsp view. The dispatch servlet will call error.jsp and
pass the model object with ’err’ attribute to the view. Then error message is
shown to the user.

1 <% @ page language = " java " contentType = " text / html ; charset = ISO -8859 -1 "
2 pageEncoding = " ISO -8859 -1 " % >
3 <! DOCTYPE html >
4 < html >
5 < head >
6 < meta charset = " ISO -8859 -1 " >
7 < title > sit218 Secure Coding - Webapp </ title >
8 </ head >
9 < body >
10 <h1 > Oops !!! </ h1 >
11 <p > $ { err } </p >
12
13 </ body >
14
15
16 </ html >

Code-3: Error page

References
• https://www.baeldung.com/java-exceptions
• https://sematext.com/blog/logging-levels/

• https://www.baeldung.com/slf4j-with-log4j2-logback
• https://docs.spring.io/spring-framework/reference/web/
webmvc/mvc-controller/ann-exceptionhandler.html

You might also like