0% found this document useful (0 votes)
5 views

Java2-02Exceptions

Uploaded by

wel24065
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java2-02Exceptions

Uploaded by

wel24065
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Exceptions

Handling

1
Java Exceptions
• When executing Java code, different
errors can occur: coding errors made by
the programmer, errors due to wrong
input, or other unforeseeable things.

• When an error occurs, Java will normally


stop and generate an error message. The
technical term for this is: Java will
throw an exception (throw an error).

22
EXCEPTIONS

3
Advantage of Exception Handling

The core advantage of exception handling is to maintain the


normal flow of the application.

statement 1;
statement 2;
statement 3;
statement 4;
statement 5; // Exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

4
• Suppose there are 10 statements in your program and there
occurs an exception at statement 5, the rest of the code will
not be executed i.e. statement 6 to 10 will not be executed.

• If we perform exception handling, the rest of the statement


will be executed. That is why we use exception handling in
Java.

5
Subclasses of The Exception
The Exception class has two main subclasses: IOException
class and RuntimeException Class.

6
Java Exception Categories

• Checked exceptions

• Unchecked exceptions

• Errors

7
Java Checked Exceptions

A checked exception is an exception that is checked


(notified) by the compiler at compilation-time, these are
also called as compile time exceptions. These exceptions
cannot simply be ignored, the programmer should take
care of (handle) these exceptions.

Example: Checked Exceptions in Java

For example, if you use FileReader class in your program


to read data from a file, if the file specified in its constructor
doesn't exist, then a FileNotFoundException occurs, and
the compiler prompts the programmer to handle the
exception.
8
Checked Exception Example

import java.io.File;
import java.io.FileReader;

public class FilenotFound_Demo {


public static void main(String args[]) {
File file = new File("E:\\file.txt");
FileReader fr = new FileReader(file);
}
}

9
Java Unchecked Exceptions
An unchecked exception is an exception that occurs at the
time of execution. These are also called as Runtime
Exceptions. These include programming bugs, such as logic
errors or improper use of an API. Runtime exceptions are
ignored at the time of compilation.

Example: Unchecked Exceptions in Java

For example, if you have declared an array of size 5 in your


program, and trying to call the 6th element of the array then an
ArrayIndexOutOfBoundsExceptionexception occurs.

10
Unchecked Exception Example

public class Unchecked_Demo {

public static void main(String args[]) {


int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}

11
Java Errors

These are not exceptions at all, but problems that arise


beyond the control of the user or the programmer. Errors
are typically ignored in your code because you can rarely
do anything about an error. For example, if a stack
overflow occurs, an error will arise. They are also ignored
at the time of compilation.

12
Exception handlers

13
Java Exceptions keywords

Here are some keywords for exception handling:


- try to place a code that may cause an error
- Catch is used to handle certain errors
- finally recover the opened inside the try block
- throws is used to declare a certain method May
throw an exception
- throw Throw a specific exception Object

1414
try...catch Example - 1

public class Main {


public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

1515
try...catch Example - 2

• public class Test {


• public static void main(String[] args) {
• try {
• int myNumbers = 2 / 0;
• System.out.println(myNumbers);
• } catch (ArithmeticException e) {
• System.out.println(“Division by zero.");
• System.out.println("e: string: "+e.toString());
• System.out.println("e: message: "+e.getMessage());
• } finally {
• System.out.println("The 'try catch' is finished.");
• }
• }
• }
1616
Multiple Catch Blocks

try {
try-block
} catch(ExceptionClass1 e) {
catch-block
} catch(ExceptionClass2 e) {
catch-block
} finally {
finally-block
}

1717
use multiple try/catch statements

try {
file = new FileInputStream(fileName);
x = (byte) file.read();
} catch (IOException i) {
i.printStackTrace();
return -1;
} catch (FileNotFoundException f) // Not valid! {
f.printStackTrace();
return -1;

18
The Throws/Throw Keywords

If a method does not handle a checked exception, the method


must declare it using the throws keyword. The throws keyword
appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or


an exception that you just caught, by using the throw
keyword.

Try to understand the difference between throws and throw


keywords, throws is used to postpone the handling of a
checked exception and throw is used to invoke an exception
explicitly.

19
Example - 1

The following method declares that it throws a RemoteException

import java.io.*;
public class className {
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
// Remainder of class definition
}

20
Example - 2

A method can declare that it throws more than one exception,


in which case the exceptions are declared in a list separated
by commas.

import java.io.*;
public class className {
public void withdraw(double amount) throws
RemoteException, InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}

21
Throws Example
class Main { // declareing the type of exception public static
void findFile() throws IOException {
// code that may generate IOException
File newFile = new File("test.txt");
FileInputStream stream = new
FileInputStream(newFile);
}
public static void main(String[] args) {
try {
findFile();
} catch (IOException e) {
System.out.println(e);
}
}
} 2222
The throw keyword

public class Main {


static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied –
You must be at least 18 years old."); }
else {
System.out.println("Access granted - You are
old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
2323
throw

24
What happens exception…

2525
Exceptions

26
Exception Propagation Example
class TestExceptionPropagation1{
void m(){ int data=50/0; }
void n(){ m(); }

void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExceptionPropagation1();
obj.p();
System.out.println("normal ow...");
}
}
27
Exception Propagation Example

Exception can be handled in any method in call stack either


in the main() method, p() method, n() method or m() method.

28
updating elements
public static void main(String[] args) throws IOException {
ArrayList<String> colors = new ArrayList<String>();
colors.add("While");
colors.add("Black");
colors.add("Yellow");
colors.add("Green");
colors.set(0, "Red");

for(String str:colors)
System.out.println(str);
}

29

You might also like