0% found this document useful (0 votes)
3 views34 pages

Java Exception Handling Explained

The document provides an overview of exception handling in Java, detailing the types of exceptions, the exception class hierarchy, and the keywords used for handling exceptions such as try, catch, finally, throw, and throws. It emphasizes the importance of separating error checking from main program logic and includes best practices for exception handling. Additionally, it covers creating custom exceptions and the significance of stack traces for debugging.

Uploaded by

eramchegyt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views34 pages

Java Exception Handling Explained

The document provides an overview of exception handling in Java, detailing the types of exceptions, the exception class hierarchy, and the keywords used for handling exceptions such as try, catch, finally, throw, and throws. It emphasizes the importance of separating error checking from main program logic and includes best practices for exception handling. Additionally, it covers creating custom exceptions and the significance of stack traces for debugging.

Uploaded by

eramchegyt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

EXCEPTIONS

SoftServe Confidential

AGENDA

• Exception Class Hierarchy


• Exception Handling
• Statements throws and throw
• Creating own Exception
• Stack Trace
SoftServe Confidential

Errors are Natural

Any software solution faces errors: invalid user input, broken connection or bugs in
code
Errors break normal flow of the program execution and may lead to fatal results in
case if not handled properly
General Kinds of Programming Errors

Compilation Errors - prevent program from running

Run-time errors - occur while program runs


Logic Errors - prevent program from doing what it is intended to do
SoftServe Confidential

Exception in Java

Lots of error checking in code makes the code harder to understand


more complex
more likely that the code will have errors!

Add error checking to the following code


BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
int k = [Link]([Link]( )); // ???

int i = 4; int j = 0;
[Link]("Result: "+ (i / j)); // ???

int[ ] a = new int[2];


a[2] = 0; // ???
SoftServe Confidential

What is Exception and Exception Handling?

Exception – is an event, which occurs during the execution of a program, that


disrupts the normal flow of the program's instructions.
Exception handling is convenient way to handle errors

normal flow: operation 1 operation 2 operation 3

exception

exception handling: operation 1 operation 2


SoftServe Confidential

Exceptions Hierarchy
Separate the error checking code from the main program code - the standard
approach since the 1980’s
SoftServe Confidential

Exception Class Hierarchy

Exceptions are the result of problems in the program.


Errors represent more serious problems associated with the JVM-level problems.
Exceptions are divided into three types:
Checked exceptions;
Unchecked exceptions, include Errors;
RuntimeExceptions, a subclass of Exception.
Checked exceptions are errors that can and should be handled in the program.
This type includes all subclasses of Exception (but not RuntimeException).
Unchecked exceptions does not require mandatory handling.
SoftServe Confidential

Exception Class Hierarchy

1. Checked exceptions
•recovery should be possible for these types of errors
•your code must
•include try-catch blocks for these or the compiler will reject
your program (e.g. IOException)
•add throws to method declaration
2. Unchecked exceptions
subclasses of RuntimeException
exceptions of this type usually mean that your program should
terminate
the compiler does not force you to include try-catch blocks for
these kinds of exceptions (e.g. ArithmeticException)
SoftServe Confidential

Exception Handling

There are five key words in Java for working with exceptions:
• try - this keyword is used to mark the beginning of a block of code that can
potentially lead to an error.
• catch - keyword to mark the beginning of a block of code designed to
intercept and handle exceptions.
• finally - keyword to mark the beginning of a block of code, which is optional.
This block is placed after the last block 'catch'. Control is usually passed to
block 'finally' in any case.
• throw - helps to generate exceptions.
• throws - keyword that is prescribed in the method signature, and is indicating
that the method could potentially throw an exception with the specified type.
SoftServe Confidential

Exception Handling

• The programmer wraps the error-prone code inside a try block.


• If an exception occurs anywhere in the code inside the try block, the catch
block is executed immediately
• the block can use information stored in the e object
• After the catch block (the catch handler) has finished, execution continues
after the catch block (in more-statements).
• execution does not return to the try block
• If the try block finishes successfully without causing an exception, then
execution skips to the code after the catch block
SoftServe Confidential

Exception in Java

Java uses exception handling


Format of code: a try block

statements;
try { a catch block
code...;
}
catch (Exception-type e) {
code for dealing with e exception
}
more-statements;
SoftServe Confidential

Exception Handling

int doSomthing(int n) {
try {
// If n = 0, then causes ArithmeticException
return 100 / n;
} catch (ArithmeticException e) {
// catch exception by class name
[Link]("Division by zero");
return 0;
}
}
SoftServe Confidential

Many catch blocks

Code fragment may contain several problem places.


For example, except for division by zero error is possible array indexing.
Need to create two or more operators catch for each type of exception.
They are checked in order.
If an exception is detected at the first processing unit, it will be
executed, and the remaining checks will be skipped.
If using multiple operators catch handler subclasses exceptions should be
higher than their handlers superclasses.
SoftServe Confidential

Exception Handling

try {
// Malicious code
} catch (ExceptionType1 e1) {
// Exception handling for the class ExceptionType1
} catch (ExceptionType2 e2) {
// Exception handling for the class ExceptionType2
} catch (Exception allAnotherExceptions) {
// Handle all exceptions previously untreated
} catch (Throwable allAnotherErrorsAndExceptions) {
/* Process all errors and exceptions that have
not been treated so far. Bad because
it also handled Error- classes */
}
SoftServe Confidential

Exception Handling

The new design is now available in Java 7, which helps you to catch a few
exceptions with one catch block :
try {
...
} catch( IOException | SQLException ex ) {
[Link](ex);
throw ex;
}
This is useful when error handling is no different.
SoftServe Confidential

Exception Handling

public int div() {


BufferedReader br = new BufferedReader( new
InputStreamReader([Link]));
try {
int n = [Link]([Link]());
int k = [Link]([Link]());
return n / k;
} catch (NumberFormatException | IOException e) {
return -1; This code does not compile
try {
} catch (ArithmeticException e) { ... }
return -2; catch (Exception e) {
} catch (Exception e) { return -1;
}
return -3; } catch (ArithmeticException e)
} {
return -2;
}
SoftServe Confidential

Finally

•A finally clause is executed even if a return statement is executed in the try or


catch clauses.
•An uncaught or nested exception still exits via the finally clause.
•Typical usage is to free system resources before returning, even after throwing an
exception (close files, network links)
try {
// Protect one or more statements here
}
catch(Exception e) {
// Report from the exception here
}
finally {
// Perform actions here whether
// or not an exception is thrown
}
SoftServe Confidential

Java 7 Resource Management


Java 7 has introduced a new interface [Link] which is extended by
[Link] interface. To use any resource in try-with-resources, it must implement
AutoCloseable interface else java compiler will throw compilation error.
public class MyResource implements AutoCloseable{
@Override
public void close() throws Exception {
[Link]("Closing");
}
MyResource sr = new MyResource();
}
try {
//doSomething with sr
} finally {
if (sr != null) { [Link](); }
}
try (MyResource sr = new MyResource()) {
//doSomething with sr
}
SoftServe Confidential

Statement throws

• If a method can throw an exception, which he does not handle, it must specify
this behavior so that the calling code could take care of this exception.
• Also there is the design throws, which lists the types of exceptions.
• Except Error, RuntimeException, and their subclasses.
SoftServe Confidential

Statement throws

For example

double safeSqrt(double x) throws ArithmeticException {


if (x < 0.0)
throw new ArithmeticException();
return [Link](x);
}
SoftServe Confidential

Statement throws foo() throws


calls (or returns)
void foo(double x) {
safeSqrt()
double result;
try {
result = safeSqrt(x);
} catch (ArithmeticException e) {
[Link](e);
result = -1;
}
[Link]("result: " + result);
}
SoftServe Confidential

Statement throw

You can throw exception using the throw statement


try {
MyClass myClass = new MyClass( );
if (myClass == null) {
throw new NullPointerException("Messages");
}
} catch (NullPointerException e) {
[Link]( );
[Link]([Link]( ));
}
SoftServe Confidential

Summary: Dealing with Checked Exceptions


SoftServe Confidential

Defining new exception

• You can subclass RuntimeException to create new kinds of


unchecked exceptions.

• Or subclass Exception for new kinds of checked exceptions.

• Why? To improve error reporting in your program.


SoftServe Confidential

Creating own checked exception

Create checked exception – MyException

class MyException extends Exception {


// Classic constructor with a message of error
public MyException(String msg) {
super(msg);
}
// Empty constructor
public MyException() { }
}
SoftServe Confidential

Creating own checked exception

public class ExampleException {


static void doSomthing(int n) throws MyException {
if (n > 0) { int a = 100 / n;
} else {
// Create and call exception
throw new MyException("input value is below zero!");
} }

public static void main(String[ ] args) {


try { doSomthing(-1); // try / catch block is required
} catch (MyException e1) {
[Link](e1);
} } }
SoftServe Confidential

Creating own unchecked exception

If you create your own exception class from RuntimeException, it’s not necessary
to write exception specification in the procedure.

class MyException extends RuntimeException { }

public class ExampleException {


static void doSomthing(int n) { throw new MyException( ); }
public static void main(String[ ] args) {
doSomthing(-1); // try / catch do not use
}
}
SoftServe Confidential

Limitation on overridden methods

Overridden method can't change list of exceptions declared in throws section of


parent method
We can add new exception to child class when it is a descendant of an exception
from the parent class or it is a runtime exception

public class Base {


public void doSomething() throws IOException{}
}

public class Child extends Base {


public void doSomething() throws Exception {}
}
SoftServe Confidential

Stack Trace

The exception keeps being passed out to the next enclosing block until:
a suitable handler is found;
or there are no blocks left to try and the program terminates with a stack trace

If no handler is called, then the system prints a stack trace as the program
terminates
it is a list of the called methods that are waiting to return when the exception occurred
very useful for debugging/testing

The stack trace can be printed by calling printStackTrace()


SoftServe Confidential

Stack Trace

public static void method1() throws MyException {


method2();
}
public static void method2() throws MyException {
method3();
}
public static void method3() throws MyException {
throw new MyException("Exception thrown in method3" );
}
} // end of UsingStackTrace class
SoftServe Confidential

Using a Stack Trace

// The getMessage and printStackTrace methods


public static void main( String[] args) {
try {
method1();
} catch (Exception e) {
[Link]([Link]() + "\n");
[Link]();
}
}
SoftServe Confidential

Using a Stack Trace


main()
method1()
[Link]() output method2()
method3()
Exception!!

[Link]()
output
SoftServe Confidential

Exception Handling Best Practices

Use Specific Exceptions – we should always throw and catch specific exception
classes so that caller will know the root cause of exception easily and process
them. This makes debugging easy and helps client application to handle exceptions
appropriately.
Throw early - we should try to throw exception as early as possible.
Catch late – we should catch exception only when we can handle it appropriate.
Close resources - we should close all the resources in finally block or use Java 7
block try-with-resources.
Do Not Use Exceptions to Control Application Flow

[Link]
THANKS

You might also like