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

Java - Exception handling, <span>Java  – Exception handling</span>, KandZ

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

Java - Exception handling, <span>Java  – Exception handling</span>, KandZ

Then the finally block

Java - Exception handling, <span>Java  – Exception handling</span>, KandZ

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:

Java - Exception handling, <span>Java  – Exception handling</span>, KandZ

or you must add exception to the method signature

Java - Exception handling, <span>Java  – Exception handling</span>, KandZ
89340cookie-checkJava – Exception handlingJava – Exception handling

Related posts

One Thought to “Java – Exception handling

Comments are closed.