public void thisMethodMayThrowException() throws TypeOfTheExceptionThrown {
... method body, here the exception can emerge ...
}
finally
hlídané výjimky, checked exceptions:
java.lang.Exception
throws
běhové (nehlídané) výjimky, unchecked exceptions:
java.lang.RuntimeException
a nemusejí být zachytávány.
signalizují těžce napravitelné chyby v JVM potomky
java.lang.Error
AssertionError
.Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program’s logic and cannot be reasonably recovered from at run time.
Gosling Arnold and Holmes
catch
.
Indikováno v hlavičce takové metody pomocí throws
. Příklad:
public void thisMethodMayThrowException() throws TypeOfTheExceptionThrown {
... method body, here the exception can emerge ...
}
Pokud daná hlídaná výjimka nikde v těle nemůže vzniknout, překladač to zdetekuje a vypíše:
Exception TypeOfTheExceptionThrown is never thrown in thisMethodMayThrowException
private static void openFile(String filename) throws IOException {
System.err.println("Trying to open file " + filename);
FileReader r = new FileReader(filename);
// success, now do further things
}
public static void main(String[] args) {
try {
openFile(args[0]);
System.err.println("File opened");
} catch (IOException ioe) {
System.err.println("Cannot open file");
}
}
Exception
(např. OverloadedException
).finally
finally
může následovat ihned po bloku try
nebo až po blocích catch
.Slouží k "úklidu v každém případě", tj.
catch
,finally
(1)public class NotEnoughParametersException extends Exception {
private int countParam;
public NotEnoughParametersException(int countParam) {
this.countParam = countParam;
}
// ...
}
finally
(2)try {
if (countParam < 2) // we can throw exception directly
throw new NotEnoughParametersException(countParam);
// here we go unless an exception thrown
System.out.println("Correct number of params: " + countParam);
} catch (NotEnoughParametersException mp) {
// here we go in case an exception is thrown
System.out.println("Less parameters than needed: " + mp.getCountParam());
} finally {
// here we go always
System.out.println("End");
}
/