Week 12 — What is an Exception?
Question of the Week #12
What is an Exception?
11 Replies
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
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.
Then you will meet those errors!
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.
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!
- 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
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
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:
Submission from Giotsche#5027
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
Exceptions are Java objects used to manage errors. They can be bypass by using try catch block or threw to stop the program.
Submission from Maruvert#2038
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
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
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).
To fix this, use a try/catch statement
Submission from MinecraftMan1013#7242
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
Exception
s 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:
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.
It is possible to catch multiple types of exceptions in a single catch-block:
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.
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).
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
):
When running it, it prints the following stack trace to System.err
:
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