Java – Exception handling

Exception handling separates the normal processing from the “anomalous” processing. If an error occurs an exception can be thrown to notify that there is a problem, catches the exception and act appropriately, it can log, exit or interact with the user. You must use a try block to catch any exceptions.

syntax:

try
  statements that may throw an exception
 catch (Exception e)
  statements that handle the exception.
finally
  statements that will always run regardless of throwing an exception or not
  • to catch every possible type of error use:
catch (Throwable t)
  • to catch every possible type of exception use:
catch (Exception e)

You can have more than one catch block.

There are two types of exceptions, checked and unchecked exceptions. Checked exceptions extend the Exception class. A method that throws a checked exception or calls a method that declares a checked exception, requires to provide an exception handler. Unchecked exceptions extend Runtime Exception and methods can handle the exception but it is optional.

public void someMethod() throws AnException

You can report/throw an exception with

throw new SomeExceptions(parameters);

The following code says Unhandled exception: java.io.FileNotFoundException

That means we need a try-block and add catch clauses. In IntelliJ prest Alt+Enter and select Add catch clause(s)

Then the finally block

On close there is an other warning Unhandled exception: java.io.IOException. You need to handle this exception too. Or you surround it with try-block:

or you must add exception to the method signature

Java – Exception handling

Read More

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s