Java Exception Handling: Understanding Exceptions in Java and Their Categories - Prof. Lou, Study notes of Computer Science

An overview of java exceptions, their difference from errors that compilers catch, and the benefits of using exceptions instead of return values. It also covers the creation and handling of exceptions, as well as the difference between checked and unchecked exceptions. Examples and explanations of the try statement, catch clauses, and the finally block.

Typology: Study notes

Pre 2010

Uploaded on 08/31/2009

koofers-user-l7b
koofers-user-l7b 🇺🇸

10 documents

1 / 6

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Programming I Java
Exceptions Handling in Java
Exceptions in Java
Compilers catch errors that occur at compilation time but not runtime errors. Java tries to deal with
runtime error as well by using exception handlers.
Exception = error in the program that occurs during its execution and disrupts the normal flow of
instructions. Exception is a shorthand for exceptional event. Examples: division by zero, trying to
access an out-of-bounds array elements, trying to open a file that does not exists, etc.
Java tries to deal with errors in a more unified manner. When such an error occurs an exception
object is created. This object contains information about the type of the error and the state of the
program when the error occurred. The exception object is then passed to the runtime system and it
is responsible to find some code to handle the error.
Why use exceptions instead of return values?
Forces error checking
Cleans up your code by separating the normal case from the exceptional case.
(The code isn't littered with a lot of if-else blocks checking return values.)
Low overhead for non-exceptional case
Separating Error Handling Code from "Regular" Code
Propagating Errors Up the Call Stack
Grouping Error Types and Error Differentiation
Throwing an exception - in Java terms - creating an exception object and handling it to the runtime
system to process it. Look at this later
Exceptions
An exception is an object that describes an unusual or erroneous situation
Exceptions are thrown by a program, and may be caught and handled by
another part of the program
A program can therefore be separated into a normal execution flow and an
exception execution flow
An error is also represented as an object in Java, but usually represents a
unrecoverable situation and should not be caught
A program can deal with an exception in one of three ways:
oignore it
ohandle it where it occurs
ohandle it an another place in the program
The manner in which an exception is processed is an important design
consideration
Louis Henry Page 1 30/11/2020
pf3
pf4
pf5

Partial preview of the text

Download Java Exception Handling: Understanding Exceptions in Java and Their Categories - Prof. Lou and more Study notes Computer Science in PDF only on Docsity!

Exceptions Handling in Java

Exceptions in Java Compilers catch errors that occur at compilation time but not runtime errors. Java tries to deal with runtime error as well by using exception handlers. Exception = error in the program that occurs during its execution and disrupts the normal flow of instructions. Exception is a shorthand for exceptional event. Examples: division by zero, trying to access an out-of-bounds array elements, trying to open a file that does not exists, etc. Java tries to deal with errors in a more unified manner. When such an error occurs an exception object is created. This object contains information about the type of the error and the state of the program when the error occurred. The exception object is then passed to the runtime system and it is responsible to find some code to handle the error. Why use exceptions instead of return values?  Forces error checking  Cleans up your code by separating the normal case from the exceptional case. (The code isn't littered with a lot of if-else blocks checking return values.)  Low overhead for non-exceptional case  Separating Error Handling Code from "Regular" Code  Propagating Errors Up the Call Stack  Grouping Error Types and Error Differentiation Throwing an exception - in Java terms - creating an exception object and handling it to the runtime system to process it. Look at this later Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown by a program, and may be caught and handled by another part of the program  A program can therefore be separated into a normal execution flow and an exception execution flow  An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught  A program can deal with an exception in one of three ways: o ignore it o handle it where it occurs o handle it an another place in the program  The manner in which an exception is processed is an important design consideration

Exception Handling  If an exception is ignored by the program, the program will terminate and produce an appropriate message  The message includes a call stack trace that indicates on which line the exception occurred  The call stack trace also shows the method call trail that lead to the execution of the offending line Categories of Exceptions  Checked Exceptions versus Unchecked  Checked exception :  Must either be caught or declared within the method where it is thrown.  Monitored by the Java compiler & Run-time.  Example: IOException Unchecked exceptions:  belong to a subclass of RuntimeException.  Not monitored by the compiler.  are subclasses of the RuntimeException class.  do NOT need to be handled in order for the program to compile.  do need to be handled if you don't want your program to die when an exception is thrown. Example: This program below will throw an ArithmeticException when the divide() method is called with zero as the denominator. Since ArithmeticException is a subclass of RuntimeException, it is an unchecked exception. This program below will compile, but when it runs an ArithmeticException will be thrown.And since this rithmeticException is not handled, the program will die.

try { // code that might generate exceptions } catch ( Exception1 ex1 ) { // handle exceptions of type Exception } catch ( Exception2 ex2 ) { // handle exceptions of type Exception } catch ( Exception3 ex3 ) { // handle exceptions of type Exception } … // etc. Key to Remember Exceptions can be handled in 2 ways:

  1. Catch the exception in the method in which it is thrown
  2. Append a clause to the method signature that notifies users that the method may throw an exception This program demonstrates the first way: catch the exception in the method in which it is thrown. public class UncheckedTwo { public static void main(String[] args) { int qa = divide(5, 2); System.out.println(qa); int qb = divide(5, 0); System.out.println(qb); } public static int divide(int numerator, int denominator) { int result = 0; try { result = numerator/denominator; } catch(ArithmeticException ex) { System.out.println(ex); result = 0; } return result; } }

In the try block you "try" your various method calls here. In the catch block you code the exception handlers. The handlers must appear directly after the try block. If an exception is thrown, the exception handling mechanism goes hunting for the first handler with an argument that matches the type of the exception. Then it enters that catch clause, and the exception is considered handled. The search for handlers stops once the catch clause is finished. Only the matching catch clause executes. Within the try block, a number of different method calls might generate the same exception, but you need only the handler. Finally Block The finally block is actually a catch block and it is optional; if it is present it is placed after the last of a try block's catch blocks: try { // code that might generate exceptions } catch ( Exception1 ex1 ) { // handle exceptions of type Exception } catch ( Exception2 ex2 ) { // handle exceptions of type Exception } catch ( Exception3 ex3 ) { // handle exceptions of type Exception } finally { // free the resources } Java guarantees that a finally block (if one is present) will be executed regardless of whether or not any exception is thrown in a try block or any of tits corresponding catch blocks. Java also guarantees that a finally block will be executed if a try block is exited via a return, break or continue statement. Resource-release code is placed in a finally block. Suppose a resource is allocated in a try block. If no exception occurs, the catch handlers are skipped and control proceeds to the finally block, which frees the resource and control proceeds to the first statement after the finally block. Standard Java Exceptions Java contains a class called Throwable that describes everything that can be thrown as an exception. Java exceptions are packages, libraries and methods specific.