try-catch
try
block.catch
block.try{
...
//call a function that may throw an exception.
...
}
catch (ExceptionType e){
...
//examine the exception and handle accordingly.
...
}
If try
encounters an exception, rest of the code in that block is skipped.
If the exception matches the type in catch
, handler code executes.
What happens if type does not match? → Called Uncaught Exception
If no one who called the code catches (or handles) the code, it reaches the top level → Main
We can catch more that one type of exception (that could be generated from the try
block)
try{
//code that might throw some exception
}
catch(FileNotFoundException e){
//Handler code
}
catch(UnknownHostException e){
//Handler code
}
catch(IOException e){
//Handler Code
}
<aside> 💡 Exception are classes in the Java class hierarchy.
</aside>
catch (ExceptionType e)
matches any subtype of ExceptionType
<aside> 💡 Catch blocks are tried in sequence.
</aside>
catch
blocks by argument type from more specifc to less specific.When does a function generate an exception?
Error
type, (Refer Here) → JVM Runtime issue