Java Error & Exceptions Flashcards
What is Exception ?
is a problem that arises during program execution.
Type of Exceptions
Checked (compiled) Exception
Unchecked(runtime) Exception
Java Error
Java errors are no exceptions at all , but problems that arises beyond control of programmer.
Examples :
*stack overflow error
*JVM out of memory
stack overflow error
Occurs when computer program tries to use more memory space at the call stack than what has been allocated to that stack
Java Exception hierarchy
All class exceptions are subclass of java.lang.Exception class.
Throwable class contain java exception class and another class called Errors
Exception two main subclasses
Exception class has two main subclasses:
*RuntimeException class
*IOException class
Some Exception class methods
*getMessage(): get details about error
*toString(): return name of class + getMessage() result
*printStackTrace():print toString() result + stack trace to System.err
try catch block
try{
//code that might throw error here
}catch(Exception e){
//handle Exception here
}
we can use multiple catch block
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
Throws/Throw keywords
if a method doesn’t handle a compilation time exception , it must declare it using “throws” keyword
to throw an exception we use “throw” keyword
=>Throws vs Throw : throws postpone/delay the handling of checked exception ,however, throw invoke an exception explicitly.
Finally Block
*Always follows try or catch block
*execute no matter what happens to protected code(try block code)
Finally Block Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
Rules of try catch finally block
*catch clause cannot exist without try statement
*finally is not necessary for try/catch block
*a try block cannot exist without catch or finally block
*no code can exist between try,catch and finally blocks
try-with-resources
when we use any resources like streams and connections… we have to close them explicitly with finally block.
try-with-resources also referred as automatic resource management automatically closes resources with try/catch blocks(without need to do it explicitly with finally block).
Syntax of try-with-resources
try(FileReader fr = new FileReader(“file path”)) {
// use the resource
} catch () {
// body of catch
}
}