- exception handling is used when the point at which an exception occurs is different from the point at which that error can or could have been corrected
- uncaught exceptions terminate the program
- the place where an exception is thrown is always different than the place it gets caught
- because you can't or don't want to fix the error in the same place where it happened
- unchecked exceptions are exceptions that happen during runtime
- unchecked exceptions are subclasses of
RuntimeException - they happen due to programmer error
- the programmer can write code to avoid these exceptions
- unchecked exceptions are subclasses of
- checked exceptions are exceptions that are explicitly thrown in the code
- checked exceptions are subclasses of
Exception - they account for things that happen that are outside of the programmer's control
- all checked exceptions must be caught or declared to be thrown
throwsis used to show that a method throws checked exceptionspublic void someMethod() throws FileNotFoundException, SomeOtherCheckedException- wherever the function is called, it has to either be in a method that is marked with
throwsor it has to catch the exception/s
- checked exceptions are subclasses of
throwindicates you've found an error, something that you can't fixtryblocks wrap code that might throw an exception- you can then
catchexceptions in the catch block - a caught exception doesn't terminate the program
- you can chain
catchblocks to catch specific exception types- when chaining, you have to put the catch blocks in order of most to least specific exception types
- e.g., put
IOExceptionafterFileNotFoundExceptionbecauseFileNotFoundExceptionis a subclass ofIOException- if you caught them in the other order,
IOExceptionfirst, allIOExceptionsandFileNotFoundExceptionswould be caught by the first block (IOException), sinceFileNotFoundExceptionis anIOException
- if you caught them in the other order,
- the
finallyblock always runs, whether an exception was thrown or not
try
{
var result = methodThatMightThrowException();
}
catch (SomeExceptionType e)
{
// handle error here
}
catch (RuntimeException e)
{
// handle error here
}
finally
{
// this code will run no matter what
}
- ???
- line endings in Unix- vs. Windows-based machines
- Windows machines end lines with
\r\n - Unix-based machines end lines with just
\n
- Windows machines end lines with