Java (11 Part Series)
1 1. Introduction to Java.. Small but worthy..
2 1.1 simple hello world program
… 7 more parts…
3 2. Installation of Java
4 3. Exercise: Write, compile and run a Java program
5 3.2. Compile and run your Java program
6 4. Base Java language structure (Class, objects, inheritance )
7 4.2 Exception handling in Java
8 5. Java interfaces
9 6. Annotations in Java
10 7. Variables and methods
11 Important announcement
In Java an exception is an event to indicate an error during the runtime of an application. So this disrupts the usual flow of the application’s instructions.
In general exceptions are thrown up in the call hierarchy until they get catched.
Checked Exceptions
Checked Exceptions are explicitly thrown by methods, which might cause the exception or re-thrown by methods in case a thrown Exception is not caught.
So when calling methods, which throw checked Exceptions the Exceptions have either to be caught or to be re-thrown
”’
public void fileNotFoundExceptionIsCaughtInside() {
try {
createFileReader();
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
}
}
public void fileNotFoundExceptionIsReThrown() throws FileNotFoundException {
createFileReader();
}
public void createFileReader() throws FileNotFoundException {
File file = new File(“/home/Documents/JavaTraining.txt”);
// creating a new FileReader can cause a FileNotFoundException
new FileReader(file);
}
”’
Checked Exceptions are used when an error can be predicted under certain circumstances, e.g., a file which cannot be found.
Runtime Exceptions
Runtime Exceptions are Exceptions, which are not explicitly mentioned in the method signature and therefore also do not have to be catched explicitly.
The most famous runtime exception is the NullPointerException, which occurs during runtime, when a method is invoked on an object, which actually is null.
”’
public void causeANullPointerException() {
String thisStringIsNull = getMessage(false);
// because the thisStringIsNull object is null
// this will cause a NullPointerException
thisStringIsNull.toLowerCase();
}
public String getMessage(boolean messageIsAvailable) {
if(messageIsAvailable) {
return message;
}
return null;
}
Java (11 Part Series)
1 1. Introduction to Java.. Small but worthy..
2 1.1 simple hello world program
… 7 more parts…
3 2. Installation of Java
4 3. Exercise: Write, compile and run a Java program
5 3.2. Compile and run your Java program
6 4. Base Java language structure (Class, objects, inheritance )
7 4.2 Exception handling in Java
8 5. Java interfaces
9 6. Annotations in Java
10 7. Variables and methods
11 Important announcement
暂无评论内容