You are on page 1of 43

Exception Handling

&
Logging Services
ADVANCED PROGRAMMING
Lecture 2

Prepared by:
Christopher Panther
Exceptions
• Interruption in normal workflow of instructions at
runtime
• Anomalous Situations (e.g. out of memory)
• Errors in data entry and value conversions
• Logical Errors
• Others
• May result in change in program execution
• Throw point – Line of code where error occurs
• Examples: ArithmaticException, NullPointerException,
ClassNotFoundException, IOException, etc.
2
Java Exception Hierarchy

3
Exception Keywords in Java
•try
•catch
•throw
•throws
•finally
4
How Exceptions May be Handled
• Locally
• In the method that throws the Exception
• Enclosed with try-catch block
• By Outer methods
• Usually handled by calling method
• Declare exceptions with method signature
• Surround forked method by try-catch
• Make JVM Handle Exception – May lead to shutdown of
application
5
Try Block
• try Block
• Monitors Code for Anomalies
• Used in conjunction with catch and / or finally

try {
//code that can throw exception
}

6
Catch Block
•Provides Exception Handling Mechanism
•May be nested
• Catch specific exceptions before generic
exceptions
•May also contain inner try blocks with catch
and / or finally blocks
•Must be used with corresponding try Block
7
Try and Catch Blocks

•So the try and the catch block work


hand in hand
•A Catch block cannot exist without a Try
Block – See next slide

8
Try - Catch

try {
//code that can throw exception
} catch(<ExceptionClassType> ex) {
//exception handling mechanism /
code
}
9
Multiple Catch Blocks

•A try may also have multiple catch blocks


•Catch blocks for different types of
exceptions
• Catch specific exceptions first
• Catch generic exceptions last
•See next Slide
10
Try – Multiple Catch Blocks
try {
//code that can throw exception
} catch(<ExceptionType1> ex ) {
//exception handling mechanism for this exception type
} catch(<ExceptionType2> ex) {
//exception handling mechanism for this exception type
} catch(Exception ex) {
//Generic exception handling mechanism
}
//NB When using multiple catch blocks, catch specific exceptions before catching
generic exceptions
11
Finally Block
• Provides instructions that must be executed
• Executed when there is an exception
• Executed when there is no exception
• Must correspond to a Try Block
• Usually used for releasing resources
• Garbage collection
• Closing Connections
• Files
• Databases
• Network

12
Try-Catch-Finally
try {
//code that can throw exception
} catch(<ExceptionType1> ex ) {
//exception handling mechanism for this exception
type
} finally {
//Code that executes regardless if an exception is
//thrown or not
}

13
Try-With-Resources
• Added in Java 7
• try statement that declares one or more resources.
• A resource is an object that must be closed after the
program is finished with it.
• The try-with-resources statement ensures that each
resource is closed at the end of the statement.
• Any object that implements java.lang.AutoCloseable
• May be used in stead of a finally block
14
Try-With-Resources Example
static String readFirstLineFromFile(String path) throws IOException {

try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}catch(IOException iex){
//Code to handle the exception
}
//No need for a finally block to close resource
}

15
Try-catch-finally Example Code

16
Try-With-Resources Example Code
Single Resource

17
Try-With-Resources Example Code
Multiple Resources
• Separate multiple resources with a semicolon

18
Throwing Exceptions
•Uses “throw” keyword
If(<Condition>) {
throw new Exception();
}

19
Custom Exceptions
•You can define your own exceptions!!
•Just extends the Exception base class
• See next slide

20
Creation of Custom Exceptions
public class MyCustomizedException extends Exception{
private String message;
public MyCustomizedException(String message) {
super(message);
this.message = message;
}
public String getMessage(){
return this.message;
}
}
21
Declaring Exceptions
• You may declare that a method throws
Exceptions
• Uses “throws” keyword
• No need to handle exception locally
• Exception handled by calling method
• Called method surrounded by Try-Catch in calling
method
22
Declaring Exceptions
public void myMethod() throws MyCustomizedException{
// valid code statements
// more valid code statements
if(<condition>) {
throw new MyCustmizedException(“error in my method”);
}
}

23
Handling Declared Exceptions, Example
public class MyExampleMainClass{
public static void main(String[] args){
ExampleClass myObj = new ExampleClass();
try{
myObj.myMethod();
}catch(MyCustomizedException mce){
mce.getMessage();
}
}
}
24
Logging
Week 2

25
Logging
• Provides an audit of events
• Errors
• Information
• Debugging
• Warnings
• Built in loggers in language
• Customized logger service
• Packaged logger (our focus)
26
Logging Packages
• Apache Log4NET (for .NET programs)
• Java.util.logging
• JBOSS Logging Service (uses log4J)
• Apache Log4J2 for Java (our focus)
• Used by other logging services
• Used by other third-party tools for logging

27
Apache Log4j2
• Download –
https://www.docs4dev.com/docs/en/log4j2/2.x/all/download.html
• Unzip apache-log4j-2.x.x to desired directory (preferably root
directory)
• Configure your project (Netbeans or Eclipse)
• Add log4J-api-2.x.x,jar AND log4j-core-2.x.x.jar to Class Path
• Create log4j2.properties file in project directory and add to Build Path
• Specify where messages are to be written to:- console, file, database
• Add external libraries/JARs
• Import org.apache.logging.log4j.* in your .java file to use log4J2
28
Log4j2 Architecture
•Loggers – Used to add entries to a log
•Appenders – Defines the output for logs
• Console
• File
• Database
•Layouts – Used to format log messages
29
Loggers
•Object that adds messages / entries to a log
• Root
• Named
•Uses Appenders
•Default Logging Level

30
Logging Levels
• TRACE – Trace Logic Flow
• DEBUG - Debugging
• INFO – General Information
• WARN – Warning for Operations
• ERROR – Errors (Great with Exceptions)
• FATAL – Errors (Requires Program Termination)
• ALL – Allow All Levels
• OFF – Turn off Logging
31
Logging Methods
• logger.trace(Object message)
• logger.debug(Object message)
• logger.info(Object message)
• logger.warn(Object message)
• logger.error(Object message)
• logger.fatal(Object message)
• logger.log(Level., “Logging Message”)
32
Layouts (log4j2)
• Used to format logging messages
• Different templates
• Pattern Layout - Uses a conversion pattern (our focus)
• HTML Layout - Formats as HTML
• CSV Layout – Formats as Comma Separated Value record
• GELF Layout (Graylog Extended Log Format)
• JSON Layout – Formats as a JSON Object
• XML Layout – Formats as XML file
33
Appenders
•Defines output for logging messages
•Logger may have multiple appenders
•Messages are logged to multiple outputs
• Console
• File
• Database
34
Appender Types
• Console Appender
• File Appender
• Rolling File Appender
• Database Appender
• Network Stream Appender
• Process Appender
• Others
35
Log4j2 Configuration
• Properties or XML File for
• Loggers
• Root
• Named (Custom)
• Appenders
• Layouts
• Should be placed in default src package
• automatically added to project classpath on build
• Value Key Pairs

36
Logger Configuration - Properties File (A)

37
Logger Configuration - Properties File (B)

38
Logger Configuration - Properties File (C)

39
Declare a log4j2 Logger
public class LoggingExample {
//Create Logger object and use the LogManager to get and assign the
//object a logger for the CLASS it is logging for

private static Logger logger =


LogManager.getLogger(LoggingExample.class);

40
Use the logger
//Use the log object to log messages
logger.info("Test Info message");
logger.debug("Test Debug Message");
logger.error(“Test Error message");
logger.trace(“Test Trace message");
logger.fatal(“Test Fatal message");
logger.warn(“Test Warning message");

41
Log4j2 Logger Program Example

42
Questions

43

You might also like