static void transferMoney(User user1, User user2, int amount) {
SomethingChecker.checkSomething(user1, user2);
user1.deduct(amount);
user1.doSomethingElse();
System.out.println("Did we get here?");
user2.add(amount);
user2.doSomeCheck();
}
public class IncorrectFileNameException extends Exception {
public IncorrectFileNameException(String errorMessage) {
super(errorMessage);
}
}
try {
// Attempt to do something where incorrect file name can be inputted.
} catch (FileNotFoundException e) {
if (!isCorrectFileName(fileName)) {
throw new IncorrectFileNameException("Incorrect filename : " + fileName);
}
// Continue handling the situation.
} finally {
// Do this in any case.
}
try {
// Attempt to do something where incorrect file name can be inputted.
} catch (FileNotFoundException e) {
if (!isCorrectFileName(fileName)) {
throw new IncorrectFileNameException("Incorrect filename : " + fileName, e);
}
// Continue handling the situation.
} finally {
// Do this in any case.
}
java.util.logging
package.<p style="text-align: center;">source: Oracle.com</p>
public class Bank {
// Obtain a logger object.
private static Logger logger = Logger.getLogger("cz.muni.fi.bank");
public static void main(String args[]) {
// Log a TRACE level message
logger.fine("Describing what I'm doing in detail.");
try {
user.withdraw(amount);
} catch (Exception ex) {
// Log the exception
logger.log(Level.WARNING, "Cannot withdraw the inputted amount.", ex);
}
logger.fine("done");
}
}
public static void main(String[] args) {
Handler fileHandler = new FileHandler("%t/bank.log");
Logger.getLogger("").addHandler(fileHandler);
Logger.getLogger("cz.muni.fi").setLevel(Level.FINEST);
...
}
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log-4j-api-version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log-4j-core-version}</version>
</dependency>
log4j2.xml
.- %d - date pattern, %p - log level, %m - message, %n - new line
---
# Logging
- And then enable it by including it among Loggers:
```xml
<Loggers>
<Root level="error">
<AppenderRef ref="logger"/>
</Root>
</Loggers>
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
public class Something {
private static Logger logger = LogManager.getLogger(Something.class);
public static void main(String[] args) {
logger.debug("Debug log message");
logger.info("Info log message");
logger.error("Error log message");
}
}
@Override
public void importData(String filePath) {
transactionExecutor.executeInTransaction(() ->
// delete data
// validate import data
// import all data
}