8.ders - İstisnai Durumlar
8.ders - İstisnai Durumlar
8.ders - İstisnai Durumlar
► Logic errors
• lead to wrong results and detected during testing.
• arise because the logic coded by the programmer was
not correct.
► Runtime errors
• Occur when the program is running, and the environment detects an
operation that is impossible to carry out.
Errors
► Code errors
• Divide by zero
• Array out of bounds
• Integer overflow
• Accessing a null pointer (reference)
1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.
What is an exception?
► An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program's instructions.
► Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code
Exceptions
► A Method in Java throws exceptions to tell the calling code:
“Something bad happened. I failed.”
What is an exception? (Example)
1- public class ExceptionExample {
2-
public static void main(String[] args) {
int dividend = 5;
3-
int divisor = 0;
4-
int division = dividend / divisor; // !!! Division
5- by zero!
6- System.out.println(" Result: " + division);
7- }
8- }
Program "crashes" on the 5th line and the output
is:
► Java run-time system creates an exception object for this condition and throws it
► This exception can be caught in order to overcome the abnormal condition and
the program and displays what went wrong and where it was. Remember the
output:
► ...
Keywords of Exception Handling
► There are five keywords in Java to deal with exceptions: try, catch,
throw, throws and finally.
► catch: Follows the try block and catches any exception which is
thrown within it.
Let’s try and catch
1- public class ExceptionExample {
2- public static void main(String[] args) {
3- try {
4- int dividend = 5;
5- int divisor = 0;
6-
int division = dividend / divisor; // !!! Division by zero!
System.out.println(" Result: " + division);
7-
} catch (Exception e) {
8-
System.out.println ("Exception occurred and
9- handled!" );
10- }
11- }
12- }
What happens when we try and catch?
► int division = dividend / divisor; statement causes an exception
► Java run-time system throws an exception object that includes data
9th line
► Output of the program is:
CloneNotSupportedException
Exception
IOException
ArithmeticException
AWTException
NullPointerException
RuntimeException
Object Throwable IndexOutOfBoundsException
…
NoSuchElementException
LinkageError
…
VirtualMachineError
Error
AWTError
► 2nd scenario: Assume that user enters value 5. What is the output of
the program? Give me an integer: 5
10 / 5 is: 2
Number is out of the array!
► 3rd scenario: Assume that user enters value 0. What is the output of
the program? Give me an integer: 0
Division by zero is not possible!
Multiple catch clauses and inheritance
► If there is inheritance between the exception classes which are
written in catch clauses;
► Exception subclass must come before any of their superclasses
► A catch statement that uses a superclass will catch exceptions of that type
plus any of its subclasses. So, the subclass would never be reached if it
comes after its superclass
..., but a new catch clause for each possible exception will
possibly make the code so complex
..., but the programmer will not know which exception was
thrown!
Confused about multiple catch clauses?
► Programmer decides on the details of the exception handling
strategy
► If it is just enough to know that something went wrong and the same
action will be taken for all exceptions (for instance; displaying a
message), then use a single catch clause with Exception!
► If it is really necessary to know which exception occurs and different
actions will be taken for each exception, then use multiple catch
clauses!
Catching Exceptions
try {
//Statements that may throw exceptions
}
catch (Exception1 exVar1) {
//code to handle exceptions of type Exception1;
}
catch (Exception2 exVar2) {
// code to handle exceptions of type Exception2;
}
...
catch (ExceptionN exVarN) {
// code to handle exceptions of type exceptionN;
}
// statement after try-catch block
Nested try statements
► A try block can include other try block(s)
try {
...
try {
...
} catch (Exception e) {
...
}
...
} catch (Exception e) {
...
}
Nested try statements
► A try block can call a method which has a try block in it.
void method() {
try {
try {
...
...
method();
} catch (Exception e) {
} catch (Exception e) {
...
...
}
}
}
Nested try statements
An exception is
thrown in
method3
► Caution! Execution flow never returns to the line that exception was
thrown. This means, an exception is caught and catch block is
executed, the flow will continue with the lines following this catch
block
Let’s clarify it on various scenarios
try { Information: Exception1 and Exception2 are
statement1; subclasses of Exception3
try {
statement2;
} catch (Exception1 e) {
Question: Which statements are executed if
statement3;
} catch (Exception2 e) { 1- statement1 throws Exception1
statement4; 2- statement2 throws Exception1
} 3- statement2 throws Exception3
try { 4- statement2 throws Exception1 and
statement5; statement3 throws Exception2
} catch (Exception3 e) {
statement6;
}
statement7;
} catch (Exception3 e) {
statement8;
}
statement9;
Scenario: statement1 throws Exception1
try { Step1: Exception is thrown
statement1; Exception1
try {
statement2;
} catch (Exception1 e) {
statement3;
} catch (Exception2 e) {
statement4;
}
try { Step2: catch clauses of the try
statement5; block are inspected for a
} catch (Exception3 e) { matching catch statement.
statement6; Exception3 is super class of
} Exception1, so it matches.
statement7;
} catch (Exception3 e) {
statement8; Step3: statement8 is executed, exception is handled and execution
} flow will continue bypassing the following catch clauses
statement9; Step4: statement9 is executed
Scenario: statement2 throws Exception1
try {
statement1;
try { Step1: Exception is thrown
statement2; Exception1
} catch (Exception1 e) {
statement3;
} catch (Exception2 e) { Step2: catch clauses of the try block are
statement4; inspected for a matching catch statement. First
} clause catches the exception
try {
statement5; Step3: statement3 is executed, exception is handled
} catch (Exception3 e) {
statement6; Step4: execution flow will continue bypassing the
} following catch clauses. statement5 is executed.
statement7;
} catch (Exception3 e) {
statement8; Step5: Assuming no exception is thrown by
} statement5, program continues with statement7
statement9; and statement9.
Scenario: statement2 throws Exception3
try {
statement1;
try { Step1: Exception is thrown
statement2; Exception3
} catch (Exception1 e) {
statement3;
} catch (Exception2 e) { Step2: catch clauses of the try block are
statement4; inspected for a matching catch statement. None
} of these catch clauses match Exception3
try {
statement5;
} catch (Exception3 e) {
statement6; Step3: Catch clauses of the outer try statement are
} inspected for a matching catch. Exception3 is
statement7; caught and statement8 is executed
} catch (Exception3 e) {
statement8;
}
statement9; Step4: statement9 is executed
Scenario: statement2 throws Exception1 and
statement3 throws Exception2
try {
statement1;
try { Step1: Exception is thrown
statement2; Exception1
} catch (Exception1 e) {
statement3; Step2: Exception is caught and statement3 is
} catch (Exception2 e) { executed.
statement4;
} Step3: statement3 throws a new exception
try { Exception2
statement5;
} catch (Exception3 e) {
statement6; Step4: Catch clauses of the outer
} try statement are inspected for a
statement7; matching catch. Exception2 is
} catch (Exception3 e) { caught and statement8 is executed
statement8;
}
statement9; Step5: statement9 is executed
finally
► finally creates a block of code that will be executed after a
try/catch block has completed and before the following try/catch
block
} finally {
statement4;
}
Step3: statement5 is executed
statement5;
Scenario: statement1 throws Exception1
try {
Step1: Exception is thrown
statement1; Exception1
} catch (Exception1 e) {
Step2: catch clauses of the try block
statement2; are inspected for a matching catch
} catch (Exception2 e) { statement. Exception1 is caught and
statement2 is executed.
statement3;
} finally { Step3: finally block is executed,
statement4 is executed.
statement4;
}
Step4: statement5 is executed
statement5;
Scenario: statement1 throws Exception3
try {
Step1: Exception is thrown
statement1; Exception3
} catch (Exception1 e) {
statement2;
} catch (Exception2 e) { Step2: catch clauses of the try block are
inspected for a matching catch statement.
statement3; There is no matching catch. finally is
} finally { executed before inspecting the outer
block. statement4 is executed.
statement4;
}
statement5;
Step3: statement5 is not executed, a matching catch will be
inspected at outer block(s)
throw
► Developer can throw exceptions. Keyword throw is used for this
purpose:
throw ThrowableObject
Developer can create a new object of an exception class, or rethrow the caught
exception
Throwing and rethrowing example
import java.util.Scanner;
Example:
catch(ArithmeticException e) {
System.out.println("Exception is: " + e);
}
Output:
Exception is: java.lang.ArithmeticException: / by zero
Getting data from the exception object
► Throwable class also has useful methods. One of these methods is the
getMessage() method
► The message that is put in the exception (via the constructor with String
parameter) can be taken by getMessage() method
Example:
catch(ArithmeticException e) {
System.out.println("Problem is: " + e.getMessage());
}
Output:
Problem is: / by zero
Getting data from the exception object
► Another method is the printStackTrace() method
► This method is used to see what happened and where
Example:
catch(ArithmeticException e) {
e.printStackTrace();
}
Output:
java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:6)
This output means:
A java.lang.ArithmeticException occurred at 6th line of the main method of
the ExceptionExample class
Did you recognize that... ?
► The output of the printStackTrace() method is very similar to the
output you have seen before...
CloneNotSupportedException
Exception
IOException
ArithmeticException
AWTException
NullPointerException
RuntimeException
Object Throwable IndexOutOfBoundsException
…
NoSuchElementException
LinkageError
…
VirtualMachineError
Error
AWTError
…
Internal errors of the JVM
Unchecked exceptions
Checked exceptions
What does Checked Exception mean?
► If a method will possibly throw an exception, compiler checks the type
of the exception
► if the exception is a checked exception, compiler forces the developer
to do one of these:
► write a matching catch statement for that exception
► declare that the method will possibly throw that exception
Handling Checked Exceptions
► Java forces you to deal with checked exceptions.
(a) (b)
throws
► Keyword throws is used to declare that a method is capable of throwing exception(s)
► Callers of the method can guard themselves against that exception(s)
Examples:
public void m1() throws Exception1 {
}