Exception handling

- Added another use case of try-with-resources
This commit is contained in:
Tristan B. Velloza Kildaire 2023-09-10 14:31:23 +02:00
parent 469495c1e8
commit 72d8f01350
1 changed files with 34 additions and 2 deletions

View File

@ -6,7 +6,7 @@ package ocp.exceptions.Exceptions;
*/
public class App
{
public static void main( String[] args )
public static void main( String[] args ) throws Exception
{
/**
* Let's do a basic exception handling here
@ -45,7 +45,7 @@ public class App
*/
catch(RuntimeException | IllegalAccessException e)
{
System.out.println("Multi-catch caught a : "+e.getClass());
}
@ -60,6 +60,9 @@ public class App
*
* If we have an error, the catch TRY first
* closes the resources and THEN runs the catch block
*
* After a caught exception OR lack thereof
* FINALLY blocke then runs
*/
try(
Box b1 = new Box();
@ -76,5 +79,34 @@ public class App
{
System.out.println("Done, no errors");
}
/**
* A cool thing one can do is have closes
* but handle exceptions elsewhere (no catch).
*
* We do this below.
*/
noCatchButCloses();
}
/**
* A neat thing to do is to use try-with-resources
* but to not catch but rather let the exception
* trickle upwards with a <code>throws</code>
* attribute
*
* @throws Exception on error with the box
*/
private static void noCatchButCloses() throws Exception
{
try
(
Box b1 = new Box();
)
{
b1.bad();
}
}
}