Week 12 — What is an Exception?

Question of the Week #12
What is an Exception?
11 Replies
Eric McIntyre
Eric McIntyre2y ago
During program execution, there are cases where the program cannot cope with a certain situation due to some reason, resulting in abnormal termination or the appearance of an error pop-up window. Such situations are called program errors. Exception handling is a way of dealing with errors that occur during the execution of a program. I will explain as point of Java. We can separate error by occurrence timing which write code -> compile -> running. There are compile error, runtime error, and logical error. 1. Compile error - Errors that occur during the compilation process are called compile-time errors. The compiler checks for errors such as typos, incorrect syntax, and data type errors in the source code during the compilation process. If the issues at this point are resolved and the compilation is successful, a class file (*.class) is generated. As you can see, i just made compile error intentionally String -> STring
void make_compile_error() {
String email = "[email protected]";
STring prefix = "This is my email : ";

System.out.println(email + prefix);
}
void make_compile_error() {
String email = "[email protected]";
STring prefix = "This is my email : ";

System.out.println(email + prefix);
}
2. Runtime error - Errors that occur during program execution are called runtime errors. While the compiler can catch errors that are predictable during the compilation process, such as syntax errors or typos, it cannot catch potential errors that may occur during program execution. Therefore, even if the compilation is completed without issues and the program is executed, errors may still occur if unexpected behavior is encountered during execution.
void parseToInt(String str) {
int i = Integer.parseInt(str);
System.out.println("this is result of parsing = " + i);
}
void parseToInt(String str) {
int i = Integer.parseInt(str);
System.out.println("this is result of parsing = " + i);
}
Then you will meet those errors!
java.lang.NumberFormatException: For input string: "ex"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:786)
java.lang.NumberFormatException: For input string: "ex"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:786)
However, at Runtime error, we can separate as error and exception. Error: A serious issue that cannot be recovered once it occurs, such as running out of memory (OutOfMemoryError) or a stack overflow (StackOverflowError). Exception: A less severe issue that can be recovered from, such as an argument being null and causing a NullPointException. 3. Logical error : An error that refers to behavior that is different from what the developer intended, even though the source code compiles correctly and no runtime errors occur, is called a logic error. For example, if a button is intended to trigger a pop-up, but instead opens a new page or does nothing at all, the program may not crash or freeze, but it is not behaving as intended.
Eric McIntyre
Eric McIntyre2y ago
How can I handle Exception!? Let's go back to the code I showed. Nobody can expect what 'str' will come in, and you don't want to meet error, then you can handle this try-catch expression!
void make_compile_error() {
String str = "Too random";
try {
//write codes which exception can be expected.
System.out.println(Integer.parseInt(str));
} catch (NumberFormatException e) {
//write codes which handle NumberFormatException from the codes in try
System.out.println("THIS IS NumberFormatException : " + e.getMessage());
} catch (Exception e) {
//write codes which handle any Exception from the code in try.
System.out.println("THIS IS Exception : " + e.getMessage());
} finally {
System.out.println("THIS IS Final handling!!!");
}
}
void make_compile_error() {
String str = "Too random";
try {
//write codes which exception can be expected.
System.out.println(Integer.parseInt(str));
} catch (NumberFormatException e) {
//write codes which handle NumberFormatException from the codes in try
System.out.println("THIS IS NumberFormatException : " + e.getMessage());
} catch (Exception e) {
//write codes which handle any Exception from the code in try.
System.out.println("THIS IS Exception : " + e.getMessage());
} finally {
System.out.println("THIS IS Final handling!!!");
}
}
- Unlike other branching statements, the try-catch block cannot omit the braces ({}) even if there is only one line of code to execute. - Like other syntax, the try-catch block can have nested try-catch blocks within its block. - If an exception is not caught and handled by a catch block, it will not be handled at all. - A block used when there is logic that must be executed regardless of whether an exception occurs or not. - If no exception occurs, the finally block is executed after the try block. - If an exception occurs, the finally block is executed after the catch block for exception handling is executed, but before the exception is thrown to the calling method or the default exception handler.
Submission from Jeong#3152
Eric McIntyre
Eric McIntyre2y ago
An exception in Java is an event that occurs during the execution of a program and disrupts the normal flow of the program’s instructions. Exceptions can be caused by various reasons, such as invalid input, file not found, network error, etc. We need exceptions to handle errors and other exceptional events that may occur at run time. Exceptions allow us to separate the normal logic of the program from the error handling logic. Exceptions also provide useful information about the cause and location of the error.
Submission from ForeverMorning#6175
Eric McIntyre
Eric McIntyre2y ago
An exception is when an error occured in the code. Like a nullpointer exception, which means, as an example, that you're trying to access a variable of an object which is null. Exceptions will crash your program, unless you add a catch to your code, which will catch the exception and do what you told it to do. Here is an example:
public static void main(String[] args){
try {
Object obj = null;
System.out.PrintLn(obj.Name); //<--- This will throw an error, because the object is null
} catch(NullPointerException exception){ //<-- this will catch the exception, so the program won't crash
e.printStackTrace() //<-- this will print the error to the console
// And here you can write code, which will be executet like:
System.out.PrintLn("Sadly, this object was not set. Please define an object");
}
}
public static void main(String[] args){
try {
Object obj = null;
System.out.PrintLn(obj.Name); //<--- This will throw an error, because the object is null
} catch(NullPointerException exception){ //<-- this will catch the exception, so the program won't crash
e.printStackTrace() //<-- this will print the error to the console
// And here you can write code, which will be executet like:
System.out.PrintLn("Sadly, this object was not set. Please define an object");
}
}
Submission from Giotsche#5027
Eric McIntyre
Eric McIntyre2y ago
An exception is an error occurring on faulty or untypical code, potentially leading to the code not working as intended. There are many different exception but the one which is most encountered is the null pointer exception, which occurs when a variable either doesn't exist or it's value equals to null
Submission from Soulvenom#0749
Eric McIntyre
Eric McIntyre2y ago
Exceptions are Java objects used to manage errors. They can be bypass by using try catch block or threw to stop the program.
try {
//code
}
catch (Exception e) {
//In case of error e
}
try {
//code
}
catch (Exception e) {
//In case of error e
}
throw new Exception(); //trow an exception
throw new Exception(); //trow an exception
Submission from Maruvert#2038
Eric McIntyre
Eric McIntyre2y ago
Exception in programming is when something does not go as it should be. Similar to errors, like in methods when some arguments are null, or something fails in general. An exception can be thrown like this
throw new Exception()
throw new Exception()
Exception can have arguments in their constructors, they can be used when catched with try-catch block for debugging or more information about the exception.
Submission from BlueTree242#9734
Eric McIntyre
Eric McIntyre2y ago
An exception is when there is a problem while executing your code. There are many kinds of exceptions, and each has its own name. One very common one is a NullPointerException. I'll use an example from the Bukkit API (Minecraft).
Player player = Bukkit.getPlayer("JavaNerd");
// If a player named "" is not online, then player will be null

// If player is null, this will throw a NullPointerException
String username = player.getName();
Player player = Bukkit.getPlayer("JavaNerd");
// If a player named "" is not online, then player will be null

// If player is null, this will throw a NullPointerException
String username = player.getName();
To fix this, use a try/catch statement
Player player = Bukkit.getPlayer("JavaNerd");

String username;
try {
username = player.getName();
// `Exception e` can also be used if the exception type is unknown, or if you want to catch multiple at once
catch(NullPointerException e) {
Bukkit.broadcastMessage("JavaNerd is not online!");
}
Player player = Bukkit.getPlayer("JavaNerd");

String username;
try {
username = player.getName();
// `Exception e` can also be used if the exception type is unknown, or if you want to catch multiple at once
catch(NullPointerException e) {
Bukkit.broadcastMessage("JavaNerd is not online!");
}
Submission from MinecraftMan1013#7242
Eric McIntyre
Eric McIntyre2y ago
An exception is an error in Java, there are exceptions that are caught before the program runs, and ones that are caught while the program runs (runtime exceptions). Runtime exceptions while have a stack trace so you can see what method caused the error, and which method called it.
Submission from eliasciur#0584
Eric McIntyre
Eric McIntyre2y ago
Exceptions are special objects which can be thrown and caught. When an Exception, is thrown, the execution of the current thread stops and it tries to find a surrounding try-catch-block which catches the exception. In that matching catch-block, the thread continues with its execution. Assume the following code:
try{
throw new Exception("test");//execution stops
//everything after it would not be executed
}catch(Exception e){//this catches the exception and execution resumes here
System.out.println("caught exception with message "+e.getMessage());
}
try{
throw new Exception("test");//execution stops
//everything after it would not be executed
}catch(Exception e){//this catches the exception and execution resumes here
System.out.println("caught exception with message "+e.getMessage());
}
The exception is thrown using the throw keyword with is followed by an expression yielding the exception to throw. When the throw statement is executed, Java stops executing the code and continues with the surrounding catch-block. The thrown exception can be accessed using the variable declared in the parenthesis of the catch-block. If the thrown exception cannot be assigned to that variable, the catch-block is ignored and Java would look for another catch-block to resume execution. Exception is a non-abstract and non-final class. Custom exception types can be created by extending Exception. When an exception is thrown inside a method and not caught in the same method, Java will continue searching for a catch-block in the method which called the method throwing the exception. If a "checked" exception might be thrown in a method which does not catch it, the method needs to declare that it could throw the exception using the throws keyword. A checked exception is an Exception which does not extend RuntimeException. If a method calls another method marked with the throws keyword, it needs to either catch the exception or declare to throw that exception as well.
void someMethod(){//due to the exception being caught, this method doesn't need to declare 'throws Exception'
try{
anotherMethod();
}catch(Exception e){//Exception caught here
System.err.println("Exception has been thrown");
e.printStackTrace();//print information where exactly the exception has been thrown
}
}
void anotherMethod() throws Exception{//as thisMethodThrowsAnException() could throw a checked exception which might not have been caught, it needs to be marked with 'throws Exception'
thisMethodThrowsAnException();
}
void thisMethodThrowsAnException() throws Exception{
throw new Exception();
}
void someMethod(){//due to the exception being caught, this method doesn't need to declare 'throws Exception'
try{
anotherMethod();
}catch(Exception e){//Exception caught here
System.err.println("Exception has been thrown");
e.printStackTrace();//print information where exactly the exception has been thrown
}
}
void anotherMethod() throws Exception{//as thisMethodThrowsAnException() could throw a checked exception which might not have been caught, it needs to be marked with 'throws Exception'
thisMethodThrowsAnException();
}
void thisMethodThrowsAnException() throws Exception{
throw new Exception();
}
It is possible to catch multiple types of exceptions in a single catch-block:
class SomeException extends Exception{}
class OtherException extends Exception{}
try{
throw new SomeException();
}catch(SomeException|OtherException e){
System.out.println("exception of type "+e.getClass().getSimpleName()+" has been thrown.");
}
class SomeException extends Exception{}
class OtherException extends Exception{}
try{
throw new SomeException();
}catch(SomeException|OtherException e){
System.out.println("exception of type "+e.getClass().getSimpleName()+" has been thrown.");
}
This will catch all exceptions that can be assigned to either SomeException or OtherException. A try-finally block allows to execute code both when an exception occurs and when the try-block completes normally. For that, it doesn't matter what type of exception it is.
try{
throw new Exception();
}finally{
System.out.println("The finally block is executed both if an exception is thrown or if no exception is thrown.");
}
System.out.println("This will not be executed as the exception hasn't been caught.");
try{
throw new Exception();
}finally{
System.out.println("The finally block is executed both if an exception is thrown or if no exception is thrown.");
}
System.out.println("This will not be executed as the exception hasn't been caught.");
An extension of that concept is the so-called try-with-resources block. It is possible to create a variable of a type assignable to AutoClosable in the parenthesis of a try-block and Java will make sure that the close-method is called when the try-block terminates (either with or without an exception).
class MyAutoClosable implements AutoClosable{
@Override
public void close(){
System.out.println("resource is closed");
}
}
try(MyAutoClosable c = new MyAutoClosable()){
//do something
}//c will be closed when the try-block completes, no matter whether or not an exception has been thrown.
class MyAutoClosable implements AutoClosable{
@Override
public void close(){
System.out.println("resource is closed");
}
}
try(MyAutoClosable c = new MyAutoClosable()){
//do something
}//c will be closed when the try-block completes, no matter whether or not an exception has been thrown.
When an exception is created, it is filled with a stack trace which includes information where exactly it has been created. This is useful for debugging. To understand what a stack trace is and how it works, take the following code (Demo.java):
public class Demo implements AutoCloseable{
public static void main(String[] args){
someMethod();
}
private static void someMethod(){
try(Demo demo = new Demo()){
demo.otherMethod();
}catch(Exception e){
throw new RuntimeException(e);
}
}
private static void otherMethod() throws Exception{
throw new Exception("Something bad happened");
}
@Override
public void close(){
throw new UnsupportedOperationException("close() threw an exception");
}
}
public class Demo implements AutoCloseable{
public static void main(String[] args){
someMethod();
}
private static void someMethod(){
try(Demo demo = new Demo()){
demo.otherMethod();
}catch(Exception e){
throw new RuntimeException(e);
}
}
private static void otherMethod() throws Exception{
throw new Exception("Something bad happened");
}
@Override
public void close(){
throw new UnsupportedOperationException("close() threw an exception");
}
}
When running it, it prints the following stack trace to System.err:
Exception in thread "main" java.lang.RuntimeException: java.lang.Exception: Something bad happened
at Demo.someMethod(Demo.java:9)
at Demo.main(Demo.java:3)
Caused by: java.lang.Exception: Something bad happened
at Demo.otherMethod(Demo.java:13)
at Demo.someMethod(Demo.java:7)
... 1 more
Suppressed: java.lang.UnsupportedOperationException: close() threw an exception
at Demo.close(Demo.java:17)
at Demo.someMethod(Demo.java:6)
... 1 more
Exception in thread "main" java.lang.RuntimeException: java.lang.Exception: Something bad happened
at Demo.someMethod(Demo.java:9)
at Demo.main(Demo.java:3)
Caused by: java.lang.Exception: Something bad happened
at Demo.otherMethod(Demo.java:13)
at Demo.someMethod(Demo.java:7)
... 1 more
Suppressed: java.lang.UnsupportedOperationException: close() threw an exception
at Demo.close(Demo.java:17)
at Demo.someMethod(Demo.java:6)
... 1 more
Eric McIntyre
Eric McIntyre2y ago
This stack trace consists of lots of debugging information. At the beginning, we can see that a RuntimeException has been thrown with the message Something bad happened. It also includes information where exactly that happened in further lines. In the second line, it states that the exception has been thrown in the method someMethod in the class Demo. It even includes the line number (line 9) of the file (Demo.java) the exception has been thrown in. After it, there is another line informing where the method has been called (it was called from the main method of the class Demo in line 9 of Demo.java). Apparently, the line someMethod(); in main called someMethod() which threw the exception in the line throw new RuntimeException(e);. In the next section of the stack trace, it is shown that the exception is actually caused by another exception (which has been passed to the constructor of RuntimeException). From the stack trace, one can see that it was caused by an exception of type Exception with the message Something bad happened which occured in line 13 of Demo (throw new Exception("Something bad happened");) and how that method was called. Furthermore, the stack trace informs readers about another exception which occured. It mentions that an UnsupportedOperationException with the text close() threw an exception was thrown in the line throw new UnsupportedOperationException("close() threw an exception"); which was caused by the try-block calling close() (try(Demo demo = new Demo()){).
⭐ Submission from dan1st#7327
Want results from more Discord servers?
Add your server