Исключения. Стандартные исключения

Содержание

Слайд 2

VI. Исключения 3. Стандартные исключения

VI. Исключения
3. Стандартные исключения


Слайд 3

Неконтролируемые исключения

Неконтролируемые исключения

Слайд 4

Неверное использование ссылки null

Неверное использование ссылки null

Слайд 5

Неверное использование ссылки null public class NullPointerExceptionDemo { public static void

Неверное использование ссылки null

public class NullPointerExceptionDemo {
public static void main(String[]

args) {
String[] staff = {"Harry Hacker", "Tonny Tester", "Eve Engineer", null, "Carl Cracker"};
for(String name : staff){
System.out.println("Hello " + name.toUpperCase());
}
System.out.println();
System.out.println("Total staff members: " + staff.length);
}
}
Hello HARRY HACKER
Hello TONNY TESTER
Hello EVE ENGINEER
Exception in thread "main" java.lang.NullPointerException
at standard.NullPointerExceptionDemo.main(NullPointerExceptionDemo.java:10)
Слайд 6

Неверное приведение public class ClassCastExceptionDemo { public static void main(String[] args)

Неверное приведение

public class ClassCastExceptionDemo {
public static void main(String[] args) {
Object

obj = new Integer(10);
System.out.println("Casting Integer to String.....");
String str =(String) obj;
System.out.println("This line will never be printed");
}
}
Casting Integer to String.....
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at standard.ClassCastExceptionDemo.main(ClassCastExceptionDemo.java:9)
Слайд 7

Операция не поддерживается public class OperationNotSupportedExceptionDemo { public static void main(String[]

Операция не поддерживается

public class OperationNotSupportedExceptionDemo {
public static void main(String[] args) {

Set greetings = Collections.singleton("Hello");
for(String greeting : greetings){
System.out.println(greeting);
}
greetings.add("Hi");
greetings.add("Good morning");
for(String greeting : greetings){
System.out.println(greeting);
}
}
}

Hello
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractCollection.add(Unknown Source)
at standard.OperationNotSupportedExceptionDemo.main(OperationNotSupportedExceptionDemo.java:16)

Слайд 8

Некорректное состояние public class IllegalStateExceptionDemo { public static void main(String[] args)

Некорректное состояние

public class IllegalStateExceptionDemo {
public static void main(String[] args) {

Set staff = new TreeSet();
staff.add("Harry Hacker");
staff.add("Tonny Tester");
staff.add("Eve Engineer");
staff.add("Carl Cracker");
Iterator iter = staff.iterator();
System.out.println(iter.next());
System.out.println(iter.next());
iter.remove();
iter.remove();
}
}

Carl Cracker
Eve Engineer
Exception in thread "main" java.lang.IllegalStateException
at java.util.TreeMap$PrivateEntryIterator.remove(TreeMap.java:1119)
at standard.IllegalStateExceptionDemo.main(IllegalStateExceptionDemo.java:25)

Слайд 9

Выход за пределы массива public class IndexOutOfBoundsExceptionDemo { public static void

Выход за пределы массива

public class IndexOutOfBoundsExceptionDemo {
public static void main(String[]

args) {
int[] anArray = { 0, 100, 200, 300, 400, 500, 600, 700, 800, 900 };
for (int i = 0; i <= 10; i++) {
System.out.println(anArray[i]);
}
System.out.println();
System.out.println("Array length is: " + anArray.length);
}
}

0
100
200
300
400
500
600
700
800
900
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at standard.IndexOutOfBoundsExceptionDemo.main(IndexOutOfBoundsExceptionDemo.java:11)

Слайд 10

Неверный аргумент public class IllegalArgumentExceptionDemo { public static void main(String[] args)

Неверный аргумент

public class IllegalArgumentExceptionDemo {
public static void main(String[] args) {

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
long now = System.currentTimeMillis();
System.out.println("Current date and time: " + sdf.format(now));
sdf = new SimpleDateFormat("Hello World: MM/dd/yyyy HH:mm:ss");
now = System.currentTimeMillis();
System.out.println("Current date and time: " + sdf.format(now));
}
}

Current date and time: 04/21/2013 19:51:03
Exception in thread "main" java.lang.IllegalArgumentException: Illegal pattern character 'e'
at java.text.SimpleDateFormat.compile(Unknown Source)
at java.text.SimpleDateFormat.initialize(Unknown Source)
at java.text.SimpleDateFormat.(Unknown Source)
at java.text.SimpleDateFormat.(Unknown Source)
at standard.IllegalArgumentExceptionDemo.main(IllegalArgumentExceptionDemo.java:16)

Слайд 11

Ошибка преобразования в число public class NumberFormatExceptionDemo { public static void

Ошибка преобразования в число

public class NumberFormatExceptionDemo {
public static void main(String[]

args) {
String[] numbers = {"9", "25", "14", "11", "33", "hello world", "45"};
int total = 0;
for (String number : numbers) {
total += Integer.parseInt(number);
System.out.println("Total so far: " + total);
}
}
}

Total so far: 9
Total so far: 34
Total so far: 48
Total so far: 59
Total so far: 92
Exception in thread "main" java.lang.NumberFormatException: For input string: "hello world"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at standard.NumberFormatExceptionDemo.main(NumberFormatExceptionDemo.java:12)

Слайд 12

Проверяемые исключения


Проверяемые исключения

Слайд 13

Контролируемые исключения

Контролируемые исключения

Слайд 14

Определение класса не найдено во время выполнения java.lang.ClassNotFoundException: DoesNotExist at java.net.URLClassLoader$1.run(URLClassLoader.java:202)

Определение класса не найдено во время выполнения
java.lang.ClassNotFoundException: DoesNotExist
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at

java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at standard.ClassNotFoundExceptionDemo.main(ClassNotFoundExceptionDemo.java:13)

public class ClassNotFoundExceptionDemo {
public static void main(String args[]) {
try {
URLClassLoader loader = new URLClassLoader(new URL[] { new URL(
"file://C:/CL/ClassNotFoundException/") });
loader.loadClass("DoesNotExist");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}

Слайд 15

public class FileNotFoundExceptionDemo { public static void main(String[] args) { BufferedReader

public class FileNotFoundExceptionDemo {
public static void main(String[] args) {
BufferedReader

br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("I:\\DoesNotExist.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Файл не найден

Слайд 16

Файл не найден java.io.FileNotFoundException: I:\DoesNotExist.txt (The system cannot find the file

Файл не найден
java.io.FileNotFoundException: I:\DoesNotExist.txt (The system cannot find the file specified)
at

java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:120)
at java.io.FileInputStream.(FileInputStream.java:79)
at java.io.FileReader.(FileReader.java:41)
at standard.FileNotFoundExceptionDemo.main(FileNotFoundExceptionDemo.java:17)
Слайд 17

public class SQLExceptionDemo { static final String DB_URL = "jdbc:derby:C:/otherDirectory/myDB"; static

public class SQLExceptionDemo {
static final String DB_URL = "jdbc:derby:C:/otherDirectory/myDB";
static

final String USER = "sa";
static final String PASS = "";
public static void main(String[] args) throws SQLException {
Connection connection = null;
try {
System.out.println("Connecting to a selected database...");
connection = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected to the database");
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}

Ошибка доступа к СУБД

Слайд 18

Ошибка доступа к СУБД Connecting to a selected database... java.sql.SQLException: Database

Ошибка доступа к СУБД

Connecting to a selected database...
java.sql.SQLException: Database 'c:/otherDirectory/myDB' not

found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection40.(Unknown Source)
at org.apache.derby.jdbc.Driver40.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.Driver20.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at standard.SQLExceptionDemo.main(SQLExceptionDemo.java:21)
Caused by: java.sql.SQLException: Database 'c:/otherDirectory/myDB' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 15 more
Слайд 19

Неправильно сформированный URL java.net.MalformedURLException: unknown protocol: gttp at java.net.URL. (URL.java:574) at

Неправильно сформированный URL
java.net.MalformedURLException: unknown protocol: gttp
at java.net.URL.(URL.java:574)
at java.net.URL.(URL.java:464)
at java.net.URL.(URL.java:413)
at standard.MalformedURLExceptionDemo.main(MalformedURLExceptionDemo.java:15)

public class

MalformedURLExceptionDemo {
public static void main(String[] args) {
try {
URL url = new URL("gttp://www.google.com:80/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Слайд 20

Ошибки (Errors)


Ошибки (Errors)

Слайд 21

Ошибки (Errors)

Ошибки (Errors)

Слайд 22

Определение класса не найдено public class NoClassDefFoundErrorDemo { public static void

Определение класса не найдено

public class NoClassDefFoundErrorDemo {
public static void main(String[]

args) {
Student harry = new Student("Harry Hacker", "Applied Mathematics");
System.out.println(harry);
}
}
class Student {
private String name;
private String major;
public Student(String name, String major) {
this.name = name;
this.major = major;
}
public String toString() {
return "Student [name=" + name + ", major=" + major + "]";
}
}
Слайд 23

Определение класса не найдено F:\spaces\javase-space\06.Exceptions\bin>dir standard Volume in drive F has

Определение класса не найдено
F:\spaces\javase-space\06.Exceptions\bin>dir standard
Volume in drive F has no

label.
Volume Serial Number is 58B9-DDFE
Directory of F:\spaces\javase-space\06.Exceptions\bin\standard
01/21/2014 04:23 PM .
01/21/2014 04:23 PM ..
01/21/2014 04:20 PM 747 NoClassDefFoundErrorDemo.class
01/21/2014 04:20 PM 745 Student.class
2 File(s) 1,492 bytes
2 Dir(s) 40,497,762,304 bytes free
F:\spaces\javase-space\06.Exceptions\bin>java standard/NoClassDefFoundErrorDemo
Student [name=Harry Hacker, major=Applied Mathematics]

Student.class

Слайд 24

Определение класса не найдено F:\spaces\javase-space\06.Exceptions\bin>del standard\Student.class F:\spaces\javase-space\06.Exceptions\bin>dir standard Volume in drive

Определение класса не найдено
F:\spaces\javase-space\06.Exceptions\bin>del standard\Student.class
F:\spaces\javase-space\06.Exceptions\bin>dir standard
Volume in drive F has

no label.
Volume Serial Number is 58B9-DDFE
Directory of F:\spaces\javase-space\06.Exceptions\bin\standard
01/21/2014 04:27 PM .
01/21/2014 04:27 PM ..
01/21/2014 04:20 PM 747 NoClassDefFoundErrorDemo.class
1 File(s) 747 bytes
2 Dir(s) 40,497,766,400 bytes free
F:\spaces\javase-space\06.Exceptions\bin>java standard/NoClassDefFoundErrorDemo
Exception in thread "main" java.lang.NoClassDefFoundError: standard/Student
at standard.NoClassDefFoundErrorDemo.main(NoClassDefFoundErrorDemo.java:6)
Caused by: java.lang.ClassNotFoundException: standard.Student
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 1 more
F:\spaces\javase-space\06.Exceptions\bin>

java.lang.NoClassDefFoundError

standard\Student.class

standard/Student

Слайд 25

Переполнение стека public class StackOverflowErrorDemo { public static void RecursiveSayHello() {

Переполнение стека

public class StackOverflowErrorDemo {
public static void RecursiveSayHello() {
System.out.println("Hello World!");

RecursiveSayHello();
}
public static void main(String[] args) {
RecursiveSayHello();
}
}

Hello World!
Hello World!
Hello World!
Hello World!
Exception in thread "main" java.lang.StackOverflowError
at sun.nio.cs.SingleByte.withResult(Unknown Source)
at sun.nio.cs.SingleByte.access$000(Unknown Source)
at sun.nio.cs.SingleByte$Encoder.encodeArrayLoop(Unknown Source)
at sun.nio.cs.SingleByte$Encoder.encodeLoop(Unknown Source)
at java.nio.charset.CharsetEncoder.encode(Unknown Source)
at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.PrintStream.write(Unknown Source)
at java.io.PrintStream.print(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at standard.StackOverflowErrorDemo.RecursiveSayHello(StackOverflowErrorDemo.java:7)
at standard.StackOverflowErrorDemo.RecursiveSayHello(StackOverflowErrorDemo.java:8)

Слайд 26

Недостаточный объём памяти public class OutOfMemoryErrorDemo { public static void main(String[]

Недостаточный объём памяти

public class OutOfMemoryErrorDemo {
public static void main(String[] args)

{
int[][] bigArray = new int[10000][];
for (int i = 0; i < bigArray.length; i++) {
bigArray[i] = new int[1024*256];
System.out.println(i + " MB used");
}
}
}

239 MB used
240 MB used
241 MB used
242 MB used
243 MB used
244 MB used
245 MB used
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at standard.OutOfMemoryErrorDemo.main(OutOfMemoryErrorDemo.java:11)