Exceptions Flashcards
Exceptions
- come in two forms:
- check and unchecked
Checked Exceptions
- The term “checked” means that the compiler will look for and catch the error, and you will not be able to run your application until it’s fixed
- Exceptions: IOException, ClassNotFoundException
Unchecked exceptions
An unchecked exception will slip through, and crop up in the middle of execution, potentially killing your application if not handled.
-Runtime exception : arithmeticException, ClassCastException, IndexOutofBoundsException
Error
Errors
-have nothing to do with your Java program (have to do with the JVM like running out of memory)
try/catch block
-must have at least one catch block or final block
- the try block contains code or method invocations which can throw exceptions.
- The catch block grabs the thrown exception and executes the enclosed code.
- You can have multiple catch blocks to handle different types of exceptions differently.
- The finally block executes regardless of the outcome, even if there is a return statement in the try block.
Stacktrace
-a debug message that shows exception that occurred, its location in the code, and other lines of code affected by the exception
Multiple catch blocks
-When catching multiple exceptions in Java, each catch statement will be evaluated in order to determine if it applies to the exception being thrown (top to bottom), and only the first applicable one will actually catch the exception.
Polymorphism tree principle example
-the principle of polymorphism means that every ArithmeticException is also a RuntimeException, which is also an Exception.
The throws clause
- re-throw an exception up to the calling code
- A method declaration can have a throws clause, indicating that it may throw and will not handle certain exceptions
- a method with a throws clause is a source for checked exceptions
Handling Exceptions
- handling exceptions costs a lot of CPU (processing) time
- when performance is of utmost importance, it’s better to write code with no exceptions or risk failure
ex: video games
Exception
-Exception is a specific subclass of Throwable and it represents all possible exceptions that may occur within your program.
RuntimeException
parent class of all unchecked exceptions
How to handle checked exceptions in code?**
-By using a try/catch/finally block or by rethrowing the exception using the throws keyword.