Содержание
- throw and throws in Java
- Built-in Exceptions in Java with examples
- Встроенные исключения в Java с примерами
- Java: таймеры или задержка выполнения потока?
throw and throws in Java
throw
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
Syntax:
But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions.
The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.
Output:
Another Example:
Output:
throws
throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
Syntax:
In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways:
- By using try catch
- By using throws keyword
We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.
Output:
Explanation: In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException.
Output:
Explanation: In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello Geeks
Another Example:
Output:
Important points to remember about throws keyword:
- throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless.
- throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program.
- By the help of throws keyword we can provide information to the caller of the method about the exception.
Reference: Java – The complete Reference by Herbert Schildt
Источник
Built-in Exceptions in Java with examples
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java.
Examples of Built-in Exception:
Output:
ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
Output:
Output:
FileNotFoundException : This Exception is raised when a file is not accessible or does not open.
Output:
IOException : It is thrown when an input-output operation failed or interrupted
Output:
Output:
NoSuchMethodException : t is thrown when accessing a method which is not found.
Output:
NullPointerException : This exception is raised when referring to the members of a null object. Null represents nothing
Output:
NumberFormatException : This exception is raised when a method could not convert a string into a numeric format.
Output:
StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is either negative than the size of the string.
Output:
Some other important Exceptions
- ClassCastException
StackOverflowError
NoClassDefFoundError
ExceptionInInitializerError
Code 1:
Code 2 :
Explanation : The above exception occurs whenever while executing static variable assignment and static block if any Exception occurs.
IllegalArgumentException
Explanation:The Exception occurs explicitly either by the programmer or by API developer to indicate that a method has been invoked with Illegal Argument.
IllegalThreadStateException
Explanation : The above exception rises explicitly either by programmer or by API developer to indicate that a method has been invoked at wrong time.
AssertionError
Explanation : The above exception rises explicitly by the programmer or by API developer to indicate that assert statement fails.
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Источник
Встроенные исключения в Java с примерами
Встроенные исключения — это исключения, доступные в библиотеках Java. Эти исключения подходят для объяснения определенных ошибок. Ниже приведен список важных встроенных исключений в Java.
Примеры встроенных исключений:
- Арифметическое исключение: оно генерируется, когда в арифметической операции возникло исключительное условие.
// Java-программа для демонстрации
// ArithmeticException
public static void main(String args[])
int a = 30 , b = 0 ;
int c = a / b; // нельзя делить на ноль
System.out.println( «Result = » + c);
catch (ArithmeticException e) <
System.out.println( «Can’t divide a number by 0» );
Выход:
ArrayIndexOutOfBounds Исключение: выдается для указания на доступ к массиву с недопустимым индексом. Индекс либо отрицательный, либо больше или равен размеру массива.
// Java-программа для демонстрации
// ArrayIndexOutOfBoundException
public static void main(String args[])
int a[] = new int [ 5 ];
a[ 6 ] = 9 ; // доступ к 7-му элементу в массиве
catch (ArrayIndexOutOfBoundsException e) <
System.out.println( «Array Index is Out Of Bounds» );
Выход:
ClassNotFoundException: это исключение возникает, когда мы пытаемся получить доступ к классу, определение которого не найдено.
// Java-программа для иллюстрации
// концепция ClassNotFoundException
public static void main(String[] args)
Object o = class .forName(args[ 0 ]).newInstance();
System.out.println( «Class created for» + o.getClass().getName());
Выход:
FileNotFoundException: это исключение возникает, когда файл недоступен или не открывается.
// Java-программа для демонстрации
// FileNotFoundException
public static void main(String args[])
// Следующий файл не существует
File file = new File( «E:// file.txt» );
FileReader fr = new FileReader(file);
catch (FileNotFoundException e) <
System.out.println( «File does not exist» );
Выход:
IOException: это бросается, когда операция ввода-вывода потерпела неудачу или прервалась
// Java-программа для иллюстрации IOException
public static void main(String args[])
FileInputStream f = null ;
f = new FileInputStream( «abc.txt» );
while ((i = f.read()) != — 1 ) <
System.out.print(( char )i);
Выход:
InterruptedException: он генерируется, когда поток ожидает, спит или выполняет некоторую обработку, и прерывается.
// Java-программа для иллюстрации
// InterruptedException
public static void main(String args[])
Thread t = new Thread();
Выход:
NoSuchMethodException: t выбрасывается при доступе к методу, который не найден.
// Java-программа для иллюстрации
// NoSuchMethodException
i = Class.forName( «java.lang.String» );
Class[] p = new Class[ 5 ];
catch (SecurityException e) <
catch (NoSuchMethodException e) <
catch (ClassNotFoundException e) <
public static void main(String[] args)
Выход:
NullPointerException: это исключение возникает при обращении к членам нулевого объекта. Null ничего не представляет
// Java-программа для демонстрации NullPointerException
public static void main(String args[])
String a = null ; // нулевое значение
catch (NullPointerException e) <
Выход:
NumberFormatException: это исключение возникает, когда метод не может преобразовать строку в числовой формат.
// Java-программа для демонстрации
// NumberFormatException
public static void main(String args[])
int num = Integer.parseInt( «akki» );
catch (NumberFormatException e) <
System.out.println( «Number format exception» );
Выход:
StringIndexOutOfBoundsException: он вызывается методами класса String, чтобы указать, что индекс либо отрицателен, чем размер строки.
// Java-программа для демонстрации
// StringIndexOutOfBoundsException
public static void main(String args[])
String a = «This is like chipping » ; // длина 22
char c = a.charAt( 24 ); // доступ к 25-му элементу
catch (StringIndexOutOfBoundsException e) <
Выход:
Некоторые другие важные исключения
- ClassCastException
// Java-программа для иллюстрации
// ClassCastException
public static void main(String[] args)
String s = new String( «Geeks» );
Object o = (Object)s;
Object o1 = new Object();
String s1 = (String)o1;
StackOverflowError
// Java-программа для иллюстрации
// StackOverflowError
public static void main(String[] args)
public static void m1()
public static void m2()
NoClassDefFoundError
// Java-программа для иллюстрации
// NoClassDefFoundError
public static void main(String[] args)
System.out.println( «HELLO GEEKS» );
ExceptionInInitializerError
Код 1:
// Java-программа для иллюстрации
// ExceptionInInitializerError
static int x = 10 / 0 ;
public static void main(String[] args)
Код 2:
// Java-программа для иллюстрации
// ExceptionInInitializerError
public static void main(String[] args)
Объяснение: Вышеуказанное исключение возникает всякий раз, когда выполняется статическое присвоение переменной и статический блок, если возникает какое-либо исключение.
IllegalArgumentException
// Java-программа для иллюстрации
// IllegalArgumentException
public static void main(String[] args)
Thread t = new Thread();
Thread t1 = new Thread();
t.setPriority( 7 ); // Верный
t1.setPriority( 17 ); // Исключение
Объяснение: Исключение возникает явно либо программистом, либо разработчиком API, чтобы указать, что метод был вызван с недопустимым аргументом.
IllegalArgumentException
// Java-программа для иллюстрации
// IllegalStateException
public static void main(String[] args)
Thread t = new Thread();
Объяснение: Вышеуказанное исключение явно возникает либо программистом, либо разработчиком API, чтобы указать, что метод был вызван в неправильное время.
AssertionError
// Java-программа для иллюстрации
// AssertionError
public static void main(String[] args)
// Если х не больше или равно 10
// тогда мы получим исключение во время выполнения
Объяснение: Вышеуказанное исключение явно вызывается программистом или разработчиком API, чтобы указать, что утверждение assert не выполнено.
Эта статья предоставлена Бишал Кумар Дубей . Если вы как GeeksforGeeks и хотели бы внести свой вклад, вы также можете написать статью с помощью contribute.geeksforgeeks.org или по почте статьи contribute@geeksforgeeks.org. Смотрите свою статью, появляющуюся на главной странице GeeksforGeeks, и помогите другим вундеркиндам.
Пожалуйста, пишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по обсуждаемой выше теме.
Источник
Java: таймеры или задержка выполнения потока?
Итак, Thread.sleep(), swing.Timer или util.Timer?
Когда встаёт вопрос о том, чтобы в программе одновременно трудилось несколько процессов, Java мгновенно предоставляет замечательный выбор. Это таймеры и потоки.
Каждый из этих способов имеет свои плюсы и минусы, не лишне было проверить их «на вшивость».
Начну с остановки потоков и таймера из пакета swing. Много описывать не буду, код хорошо задокументирован.
Есть ещё ScheduledThreadPoolExecutor, но у меня уже нет сил это изучить. В документации сказано, что «Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.»
Таймеры от сторонних разработчиков не рассматриваю.
Результаты очень интересные.
Testing all timers. Now pause is 0 milliseconds.
Phase one: timers. Please wait.
Time interval in millis: 0.12545967849848738 ms
Time interval in nanos: 1,9 (ms)
Phase two: thread. Please wait.
Time interval in millis: 0.0019032733135913883 ms
Time interval in nanos: 0,0 (ms)
Testing all timers. Now pause is 1 milliseconds.
Phase one: timers. Please wait.
Time interval in millis: 0.0019258535174836652 ms
Time interval in nanos: 2,0 (ms)
Phase two: thread. Please wait.
Time interval in millis: 0.5019265826641963 ms
Time interval in nanos: 1,9 (ms)
Testing all timers. Now pause is 5 milliseconds.
Phase one: timers. Please wait.
Time interval in millis: 1.9484478393573503 ms
Time interval in nanos: 5,9 (ms)
Phase two: thread. Please wait.
Time interval in millis: 4.638530520273565 ms
Time interval in nanos: 5,9 (ms)
Testing all timers. Now pause is 10 milliseconds.
Phase one: timers. Please wait.
Time interval in millis: 5.86178019398294 ms
Time interval in nanos: 10,8 (ms)
Phase two: thread. Please wait.
Time interval in millis: 11.367928020187971 ms
Time interval in nanos: 10,7 (ms)
Testing all timers. Now pause is 15 milliseconds.
Phase one: timers. Please wait.
Time interval in millis: 10.729611829460866 ms
Time interval in nanos: 15,6 (ms)
Phase two: thread. Please wait.
Time interval in millis: 15.427355571506467 ms
Time interval in nanos: 15,6 (ms)
Testing all timers. Now pause is 20 milliseconds.
Phase one: timers. Please wait.
Time interval in millis: 15.60761994963609 ms
Time interval in nanos: 20,5 (ms)
Phase two: thread. Please wait.
Time interval in millis: 18.111812599697064 ms
Time interval in nanos: 20,5 (ms)
Testing timers. Now pause is 1 milliseconds.
Time interval in nanos: 0,0 (ms)
Testing timers. Now pause is 5 milliseconds.
Time interval in nanos: 2,3 (ms)
Testing timers. Now pause is 10 milliseconds.
Time interval in nanos: 6,7 (ms)
Testing timers. Now pause is 15 milliseconds.
Time interval in nanos: 15,5 (ms)
Testing timers. Now pause is 20 milliseconds.
Time interval in nanos: 20,0 (ms)
вторая попытка:
Testing timers. Now pause is 1 milliseconds.
Time interval in nanos: 7,9 (ms)
Testing timers. Now pause is 5 milliseconds.
Time interval in nanos: 1,1 (ms)
Testing timers. Now pause is 10 milliseconds.
Time interval in nanos: 6,7 (ms)
Testing timers. Now pause is 15 milliseconds.
Time interval in nanos: 15,6 (ms)
Testing timers. Now pause is 20 milliseconds.
Time interval in nanos: 17,7 (ms)
третья попытка:
Testing timers. Now pause is 1 milliseconds.
Time interval in nanos: 0,2 (ms)
Testing timers. Now pause is 5 milliseconds.
Time interval in nanos: 2,2 (ms)
Testing timers. Now pause is 10 milliseconds.
Time interval in nanos: 5,8 (ms)
Testing timers. Now pause is 15 milliseconds.
Time interval in nanos: 15,6 (ms)
Testing timers. Now pause is 20 milliseconds.
Time interval in nanos: 16,4 (ms)
У меня Windows XP SP3, AMD Athlon 64 X2 5000+
Теперь о времени, измеряемом в наносекундах:
Как задержка потока, так и таймер swing срабатывают практически одинаково.
Погрешность в измерении существенна при маленьких временных отрезках (+1 миллисекунда), однако, такая точность как правило не нужна. Если требуемый интервал составляет 100 миллисекунд, то оба приёма гарантируют 109, то есть погрешность примерно 9%.
Для маленьких интервалов времени работа util.Timer неприятно удивляет. Разброс результатов от запуска к запуску сильно разнится, вдобавок, погрешность измерения времени очень большая. Любопытно, что для 100 миллисекунд разброс идёт от 102 до 107, что точнее конкурирующих технологий.
Если задержка составляет 1 секунду, то результаты совсем другие. swing.Timer даёт разброс от 1030 до 1144, причём, что currentMillis, что nanoTime не гарантируют никакой точности и по очереди соревнуются кто хуже.
Для 1 секунды остановка потока работает с невероятной точностью: 999. Это 0.1%, что очень круто.
Источник
throw
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
Syntax:
throw Instance Example: throw new ArithmeticException("/ by zero");
But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions.
The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.
Java
class
ThrowExcep
{
static
void
fun()
{
try
{
throw
new
NullPointerException(
"demo"
);
}
catch
(NullPointerException e)
{
System.out.println(
"Caught inside fun()."
);
throw
e;
}
}
public
static
void
main(String args[])
{
try
{
fun();
}
catch
(NullPointerException e)
{
System.out.println(
"Caught in main."
);
}
}
}
Output:
Caught inside fun(). Caught in main.
Another Example:
Java
class
Test
{
public
static
void
main(String[] args)
{
System.out.println(
1
/
0
);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
throws
throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
Syntax:
type method_name(parameters) throws exception_list exception_list is a comma separated list of all the exceptions which a method might throw.
In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways:
- By using try catch
- By using throws keyword
We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.
Java
class
tst
{
public
static
void
main(String[] args)
{
Thread.sleep(
10000
);
System.out.println(
"Hello Geeks"
);
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
Explanation: In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException.
Java
class
tst
{
public
static
void
main(String[] args)
throws
InterruptedException
{
Thread.sleep(
10000
);
System.out.println(
"Hello Geeks"
);
}
}
Output:
Hello Geeks
Explanation: In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello Geeks
Another Example:
Java
class
ThrowsExecp
{
static
void
fun()
throws
IllegalAccessException
{
System.out.println(
"Inside fun(). "
);
throw
new
IllegalAccessException(
"demo"
);
}
public
static
void
main(String args[])
{
try
{
fun();
}
catch
(IllegalAccessException e)
{
System.out.println(
"caught in main."
);
}
}
}
Output:
Inside fun(). caught in main.
Important points to remember about throws keyword:
- throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless.
- throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program.
- By the help of throws keyword we can provide information to the caller of the method about the exception.
Reference: Java – The complete Reference by Herbert Schildt
This article is contributed by Pratik Agarwal and Bishal Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Vizlim 5 / 5 / 5 Регистрация: 24.10.2011 Сообщений: 269 |
||||
1 |
||||
Как сделать задержку выполнения цикла?07.03.2012, 14:56. Показов 11281. Ответов 14 Метки нет (Все метки)
Мне надо притормозить цикл:
^ Казалось бы простейшая ситуация, а тут……. Подскажите пожалуйста в чём ошибка и как её исправить.
__________________
0 |
0 / 0 / 4 Регистрация: 14.08.2007 Сообщений: 307 |
|
07.03.2012, 15:14 |
2 |
тебе же компилятор уже ответил на вопрос.
0 |
Vizlim 5 / 5 / 5 Регистрация: 24.10.2011 Сообщений: 269 |
||||
07.03.2012, 16:35 [ТС] |
3 |
|||
тебе же компилятор уже ответил на вопрос. При попытки дописать public A() throws InterruptedException выдаёт ошибку в создании класа JPanel, где и находиться A(); а после выдаёт ещё ряд ошибок уже связаных с InterruptedException . Если использовать связку try-catch тоже ошибка
Скорее всего я не правильно его пытаюсь отловить, хотя вроде структура верна
0 |
scroodge 0 / 0 / 4 Регистрация: 14.08.2007 Сообщений: 307 |
||||
07.03.2012, 16:52 |
4 |
|||
Ты что то путаешь. Такая кончтрукция должна компилироваться без проблем. Если ты действительно видишь какие то сообщения компилятора об ошибках — пости их сюда.
0 |
5 / 5 / 5 Регистрация: 24.10.2011 Сообщений: 269 |
|
07.03.2012, 17:24 [ТС] |
5 |
Ты что то путаешь. Такая кончтрукция должна компилироваться без проблем. Если ты действительно видишь какие то сообщения компилятора об ошибках — пости их сюда. Код int pex = 0; try { while (pex<=100) { pex+=10; repaint(); wait(1000); //задежка выполнения цикла } } catch (InterruptedException e) { // do nothing } Я прикрепил файл. Там в 67 строке и начинаеться конструкция try { }.
0 |
3 / 3 / 0 Регистрация: 25.08.2010 Сообщений: 213 |
|
07.03.2012, 18:18 |
6 |
проверять нет времени — но в данном случае по-любому надо ловить сообщение тока в вейте а не во всем циклею потому как сейчас ты вылетишь из цикла при первом же исключении, а не просто перейдешь на след итерацию
0 |
2 / 2 / 3 Регистрация: 09.07.2008 Сообщений: 422 |
|
07.03.2012, 18:28 |
7 |
Компилируется без проблем (у меня JBuilder) и работает в том виде, в каком ты выложил. Чем компилируешь?
0 |
5 / 5 / 5 Регистрация: 24.10.2011 Сообщений: 269 |
|
07.03.2012, 18:40 [ТС] |
8 |
Компилируется без проблем (у меня JBuilder) и работает в том виде, в каком ты выложил. Чем компилируешь? У меня JBuilder8, jdk 1.4 .Мне очень тяжело вериться, что у тебя не выводит ошибку, ты просто не нажимал на правую стрелочку
0 |
0 / 0 / 4 Регистрация: 14.08.2007 Сообщений: 307 |
|
07.03.2012, 19:53 |
9 |
Всё компилируется и запускается. Окно разворачивется на весь экран, появляются две человекоподобных фигурки и не видно никаких стрелок. Звиняй, разбираться с твоим кодом и пытаться понять что там со стрелочками некогда. Кстати интересно — я подозревал что жбилдер убогий тул, но неужели в нём нет даже автоформатирования кода?
0 |
5 / 5 / 5 Регистрация: 24.10.2011 Сообщений: 269 |
|
07.03.2012, 20:07 [ТС] |
10 |
Всё компилируется и запускается. Окно разворачивется на весь экран, появляются две человекоподобных фигурки и не видно никаких стрелок. Звиняй, разбираться с твоим кодом и пытаться понять что там со стрелочками некогда. Кстати интересно — я подозревал что жбилдер убогий тул, но неужели в нём нет даже автоформатирования кода? ОЙ блин……. Стрелочки на клавиатуре!!! (Вверх, вниз, влево и вправо(вот вправо я и мел в виду) )
0 |
scroodge 0 / 0 / 4 Регистрация: 14.08.2007 Сообщений: 307 |
||||
07.03.2012, 20:22 |
11 |
|||
стрелочки я уже нашёл таки
0 |
5 / 5 / 5 Регистрация: 24.10.2011 Сообщений: 269 |
|
07.03.2012, 21:12 [ТС] |
12 |
стрелочки я уже нашёл таки Код try { while (pex <= 100) { pex += 10; repaint(); synchronized (this) { wait(1000); } } } catch (InterruptedException e) { // do nothing } Read the fucking manual Большое спасибо тебе за попытку мне помочь, но пока что-то не получаеться
0 |
0 / 0 / 4 Регистрация: 14.08.2007 Сообщений: 307 |
|
07.03.2012, 21:50 |
13 |
как это «не получается» ?
0 |
5 / 5 / 5 Регистрация: 24.10.2011 Сообщений: 269 |
|
07.03.2012, 22:51 [ТС] |
14 |
как это «не получается» ? Похоже я понял, что именно мне предлагаешь. Ты хочешь что бы я создал поток, который и будет решать мои проблемы или нечто похожее по структуре на поток Ещё раз большое тебе спасибо за помощь………
0 |
trainee 0 / 0 / 1 Регистрация: 21.03.2012 Сообщений: 13 |
||||
21.03.2012, 15:38 |
15 |
|||
Вот именно через потоки такая функция и доступна. Пишешь:
Здесь никакой поток не создается, это статический метод класса, который сам определит кому спать!!!
0 |
- Reviews
- About us
- All questions
- 21.01.2019
- 2057views
- 7comments
Why the message appears?
I’m sure the code is OK
com/codegym/task/task07/task0723/Solution.java:12: error: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
Thread.sleep(100);
public class Solution {
public static void main(String[] args) {
for (int i = 30; i >= 0; i—) {
System.out.println(i);
Thread.sleep(100);
}
System.out.println(«Boom!»);
}
}
- Popular
- New
- Old
ddi
Level 18 , Dortmund
, Germany
24 June 2019, 13:39
public static void main(String[] args)
throws InterruptedException
{
You need to write throws InterruptedException for the class to recognize it!
The method Thread.Sleep has an exception that can be thrown. Because of this you either need to surround it in a catch block, or add the exception to your method signature. If you click the part that has the red squiggly in your code (sleep) and hit alt enter, IntelliJ will present you with options to solve (which will be the same i just said).
Niket
4 February 2019, 08:23
How can we surround it with the catch block that you are referring to…?? I am writing the code on the website itself not on IntelliJ
you need intelliJ. The website IDE will throw a whole bunch of false errors and provides no help with things like this. It’s impressive that you made it this far without it, but you shouldn’t even try going further until you download it.
Sokhibjon
Level 14 , Tashkent
, Uzbekistan
28 March 2019, 15:19
search for Thread.sleep example then copy the throws(exception) when you are opening the paren for main method
Kent Hervey Software Engineer/Consult at Zeal IT Consultants
Expert
22 November 2019, 05:06
Good advice about InteliJ unless a person is trying to code everywhere and that means iPad, Chromebook, library, friend’s house….I can respect that
Jeremi Nuer
Level 7 , San Francisco
, United States
30 November 2020, 23:57
I would like to use IntelliJ… but it doesn’t work for my computer. For some reason, importing the codegym version does not work for me, and doesn’t change anything. So I will have to make due with this.
Я получаю исключение при использовании Thread.sleep (x) или wait ()
Я попытался отложить или усыпить свою программу Java, но произошла ошибка.
Я не могу использовать Thread.sleep(x) или wait() . Появляется такое же сообщение об ошибке:
unreported exception java.lang.InterruptedException; must be caught or declared to be thrown.
Требуется ли какой-либо шаг перед использованием методов Thread.sleep() или wait() ?
Тебе предстоит много чтения. От ошибок компилятора до обработки исключений, потоковой передачи и прерывания потоков. Но это будет делать то, что вы хотите:
Как говорили другие пользователи, вы должны окружить свой звонок try <. >catch <. >блоком. Но с тех пор, как была выпущена Java 1.5, существует класс TimeUnit, который делает то же самое, что и Thread.sleep (millis), но более удобный. Вы можете выбрать единицу времени для спящего режима.
Также у него есть дополнительные методы: TimeUnit Oracle Documentation
Взгляните на этот отличный краткий пост о том, как это сделать правильно.
По сути: лови InterruptedException . Помните, что вы должны добавить этот блокировщик. Сообщение объясняет это немного дальше.
Используйте следующую конструкцию кодирования для обработки исключений
Поместите себя Thread.sleep в блок попытки поймать
При использовании Android (единственный раз, когда я использую Java) я бы рекомендовал использовать обработчик вместо того, чтобы переводить поток в спящий режим.
Мои способы добавить задержку в Java-программу.
Это для последовательной задержки, но для задержек цикла обратитесь к Java Delay / Wait .
Более простой способ ожидания — использовать System.currentTimeMillis() , который возвращает количество миллисекунд, прошедших с полуночи 1 января 1970 года по всемирному координированному времени. Например, подождать 5 секунд:
Таким образом, вам не придется возиться с потоками и исключениями. Надеюсь это поможет!
Спите одну секунду или
Поскольку это петля, это создает внутреннюю проблему — дрейф. Каждый раз, когда вы запускаете код, а затем засыпаете, вы будете немного отвлекаться от выполнения, скажем, каждую секунду. Если это проблема, не используйте sleep .
Кроме того, sleep не очень гибко, когда дело доходит до контроля.
Для запуска задачи каждую секунду или с задержкой в одну секунду я настоятельно рекомендую [ ScheduledExecutorService ] [1] и либо [ scheduleAtFixedRate ] [2], либо [ scheduleWithFixedDelay ] [3].
Чтобы запускать метод myTask каждую секунду (Java 8):
Источник
throw and throws in Java
throw
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
Syntax:
But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions.
The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.
Output:
Another Example:
Output:
throws
throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
Syntax:
In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways:
- By using try catch
- By using throws keyword
We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.
Output:
Explanation: In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException.
Output:
Explanation: In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello Geeks
Another Example:
Output:
Important points to remember about throws keyword:
- throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless.
- throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program.
- By the help of throws keyword we can provide information to the caller of the method about the exception.
Reference: Java – The complete Reference by Herbert Schildt
Источник
throw and throws in Java
throw
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
Syntax:
But this exception i.e, Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class. Unlike C++, data types such as int, char, floats or non-throwable classes cannot be used as exceptions.
The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.
Output:
Another Example:
Output:
throws
throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
Syntax:
In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways:
- By using try catch
- By using throws keyword
We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.
Output:
Explanation: In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException.
Output:
Explanation: In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello Geeks
Another Example:
Output:
Important points to remember about throws keyword:
- throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless.
- throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program.
- By the help of throws keyword we can provide information to the caller of the method about the exception.
Reference: Java – The complete Reference by Herbert Schildt
Источник
Built-in Exceptions in Java with examples
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in exceptions in Java.
Examples of Built-in Exception:
Output:
ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
Output:
Output:
FileNotFoundException : This Exception is raised when a file is not accessible or does not open.
Output:
IOException : It is thrown when an input-output operation failed or interrupted
Output:
Output:
NoSuchMethodException : t is thrown when accessing a method which is not found.
Output:
NullPointerException : This exception is raised when referring to the members of a null object. Null represents nothing
Output:
NumberFormatException : This exception is raised when a method could not convert a string into a numeric format.
Output:
StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is either negative than the size of the string.
Output:
Some other important Exceptions
- ClassCastException
StackOverflowError
NoClassDefFoundError
ExceptionInInitializerError
Code 1:
Code 2 :
Explanation : The above exception occurs whenever while executing static variable assignment and static block if any Exception occurs.
IllegalArgumentException
Explanation:The Exception occurs explicitly either by the programmer or by API developer to indicate that a method has been invoked with Illegal Argument.
IllegalThreadStateException
Explanation : The above exception rises explicitly either by programmer or by API developer to indicate that a method has been invoked at wrong time.
AssertionError
Explanation : The above exception rises explicitly by the programmer or by API developer to indicate that assert statement fails.
This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Источник
Resolve Unreported Exception IOException Must Be Caught or Declared to Be Thrown in Java
This tutorial demonstrates another compile time exception saying unreported exception ioexception; must be caught or declared to be thrown . We will also learn about its possible causes and solutions via sample programs.
Demonstration of Unreported IOException
In the code above, we read data from the specified input file; look for the letter x . As soon as it is found, we replace the x and the upcoming text on the same line with the word Updated enclosed in double quotes ( » » ).
Finally, we close both files (input and output).
The line inputFile.close(); that we are pointing to in the above code example is causing an unreported IOException which must be caught or thrown. What does this mean?
It means the inputFile.close(); is causing the IOException that we can get rid of using the try-catch block (it’s called catching the exception) or using the throws keyword (it’s called exception is thrown). How to do it?
Let’s learn with code examples below.
Use try-catch to Catch Unreported IOException
The input file has the following content.
After executing the program, we get an output file containing the content below.
Here, we eliminate the IOException using the try-catch block, where the try statement lets us define a specific block of code that needs to be examined for errors during the execution process.
If any exception occurs at any particular statement within the try block, it will stop execution and jump to the catch block. So, it is strongly advised not to keep the code within the try block that does not throw any exception.
On the other hand, the catch statement permits defining a block of code that needs to be executed if there is any error in the try block. The catch is written right after the try block.
We can also have multiple catch blocks based on how many exceptions we can get in the respective try block.
We can also write a customized message while handling the exception. Now, the question is how these exceptions are handled.
The Java Virtual Machine (JVM) checks whether an exception is handled or not. If it is not, the JVM serves with the default exception handler, which does a few tasks that are listed below:
- It prints the description of an exception in the program’s output console.
- It also prints the stack trace in the program’s output console. The stack trace is the methods’ hierarchy where an exception occurred.
- It results in the program’s termination.
On the other side, the application’s normal flow is maintained if an application programmer has handled the exception, which means the remaining code gets executed.
Use the throws Keyword to Eradicate IOException
The content of an input file is as follows.
The output file has the updated content as given below.
This code is the same as the previous section, where we only use the try-catch block to handle the exception. Here, we are using throws to declare an exception; we can also declare multiple exceptions separated by a comma ( , ).
The throws keyword informs the application programmer that an exception may occur in this method. Remember, the throws keyword is written while defining the function (see in the given example code).
So, it is good and strongly advised that the programmer handle this exception in the code to maintain the normal execution flow. Otherwise, the program will terminate. Let’s understand it via example code.
Copy the following code and run it. Make sure we have an incorrect path for the input file.
We will see the output as given above. The program continues code execution because we have handled the exception.
Now, comment out the try , catch , and finally blocks as follows and rerun the code. Make sure we have an incorrect path for an input file.
The program will terminate the execution as soon as it finds the exception and never reaches the following line of code.
This is the reason we handle our declared exceptions. Remember, we can only declare the checked exceptions because the programmer can handle the unchecked exceptions within the code.
Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.
Источник
Java Programming Notes # 1630
- Preface
- Preview
- Discussion and Sample Code
- Summary
- What’s Next
Preface
This series of lessons is designed to teach you about the essence of
Object-Oriented Programming (OOP) using Java.
The first lesson in the series was entitled
The Essence of OOP Using Java, Objects, and Encapsulation. The
previous lesson was entitled
The Essence of OOP using Java, The this and super Keywords.
You may find it useful to open another copy of this lesson in a separate
browser window. That will make it easier for you to scroll back and forth
among the different listings while you are reading about them.
For further reading, see my extensive collection of online Java tutorials at
Gamelan.com. A consolidated
index is available at
www.DickBaldwin.com.
Preview
This lesson explains Exception Handling in Java. The discussion
includes the following topics:
- What is an exception?
- How do you throw and catch exceptions?
- What do you do with an exception once you have caught it?
- How do you make use of the exception class hierarchy provided by the Java
development environment?
This lesson will cover many of the details having to do with exception
handling in Java. By the end of the lesson, you should know that the use
of exception handling is not optional in Java, and you should have a pretty good
idea how to use exception handling in a beneficial way.
Discussion and Sample Code
Introduction
Stated simply, the exception-handling capability of Java makes it possible
for you to:
- Monitor for exceptional conditions within your program
- Transfer control to special exception-handling code (which you design)
if an exceptional condition occurs
The basic concept
This is accomplished using the keywords: try, catch, throw,
throws, and finally. The basic concept is as follows:
- You try to execute the statements contained within a block of code.
(A block of code is a group of one or more statements surrounded by
braces.) - If you detect an exceptional condition within that block, you throw
an exception object of a specific type. - You catch and process the exception object using code that you have
designed. - You optionally execute a block of code, designated by finally,
which needs to be executed whether or not an exception occurs. (Code
in the finally block is normally used to perform some type of cleanup.)
Exceptions in code written by others
There are also situations where you don’t write the code to throw the
exception object, but an exceptional condition that occurs in code written by
someone else transfers control to exception-handling code that you write.
For example, the read method of the InputStream class throws an
exception of type IOException if an exception occurs while the read
method is executing. In this case, you are responsible only for the code
in the catch block and optionally for the code in the finally
block.
(This is the reason that you must surround the invocation of
System.in.read() with a try block followed by a catch block,
or optionally declare that your method throws an exception of type
IOException.)
Exception hierarchy, an overview
When an exceptional condition causes an exception to be thrown, that
exception is represented by an object instantiated from the class named
Throwable or one of its subclasses.
Here is part of what Sun has to say about the Throwable class:
«The Throwable class is the superclass of all errors and
exceptions in the Java language. Only objects that are instances of this class
(or one of its subclasses) are thrown by the Java Virtual Machine or can be
thrown by the Java throw statement. Similarly, only this class or
one of its subclasses can be the argument type in a catch clause.»
Sun goes on to say:
«Instances of two subclasses, Error and Exception, are
conventionally used to indicate that exceptional situations have occurred.
Typically, these instances are freshly created in the context of the
exceptional situation so as to include relevant information (such as stack
trace data).»
The Error and Exception classes
The virtual machine and many different methods in many different classes
throw exceptions and errors. I will have quite a lot more to
say about the classes named Error and Exception later in this
lesson.
Defining your own exception types
You may have concluded from the Sun quotation given above that you can define
and throw exception objects of your own design, and if you did, that is a
correct conclusion. (Your new class must extend Throwable or one of
its subclasses.)
The difference between Error and Exception
As mentioned above, the Throwable class has two subclasses:
- Error
- Exception
What is an error?
What is the difference between an Error and an Exception?
Paraphrasing David Flanagan and his excellent series of books entitled Java
in a Nutshell, an Error indicates that a non-recoverable error has
occurred that should not be caught. Errors usually cause the Java virtual
machine to display a message and exit.
Sun says the same thing in a slightly different way:
«An Error is a subclass of Throwable that indicates
serious problems that a reasonable application should not try to catch.
Most such errors are abnormal conditions.»
For example, one of the subclasses of Error is named
VirtualMachineError. This error is «Thrown to indicate that the
Java Virtual Machine is broken or has run out of resources necessary for it to
continue operating. «
What is an exception?
Paraphrasing Flanagan again, an Exception indicates an abnormal
condition that must be properly handled to prevent program termination.
Sun explains it this way:
«The class Exception and its subclasses are a form of
Throwable that indicates conditions that a reasonable application might
want to catch.»
As of JDK 1.4.0, there are more than fifty known subclasses of the
Exception class. Many of these subclasses themselves have numerous
subclasses, so there is quite a lot of material that you need to become familiar
with.
The RuntimeException class
One subclass of Exception is the class named RuntimeException
As of JDK 1.4.0, this class has about 30 subclasses, many which are further
subclassed. The class named RuntimeException is a very important
class.
Unchecked exceptions
The RuntimeException class, and its subclasses, are important not so
much for what they do, but for what they don’t do. I will refer to
exceptions instantiated from RuntimeException and its subclasses as
unchecked exceptions.
Basically, an unchecked exception is a type of exception that you can
optionally handle, or ignore. If you elect to ignore the possibility of an
unchecked exception, and one occurs, your program will terminate as a result.
If you elect to handle an unchecked exception and one occurs, the result will
depend on the code that you have written to handle the exception.
Checked exceptions
All exceptions instantiated from the Exception class, or from
subclasses of Exception other than RuntimeException and its
subclasses must either be:
- Handled with a try block followed by a catch block, or
- Declared in a throws clause of any method that can throw them
In other words, checked exceptions cannot be ignored when you write
the code in your methods. According to Flanagan, the exception classes in
this category represent routine abnormal conditions that should be anticipated
and caught to prevent program termination.
Checked by the compiler
Your code must anticipate and either handle or declare checked exceptions. Otherwise,
your program won’t compile. (These are exception types that are checked
by the compiler.)
Throwable constructors and methods
As mentioned above, all errors and exceptions are subclasses of the
Throwable class. As of JDK 1.4.0, the Throwable class provides
four constructors and about a dozen methods. The four constructors are
shown in Figure 1.
Throwable()
Throwable(String message)
Throwable(String message, Throwable cause)
Throwable(Throwable cause) Figure 1
The first two constructors have been in Java for a very long time.
Basically, these two constructors allow you to construct an exception object
with, or without a String message encapsulated in the object.
New to JDK 1.4
The last two constructors are new in JDK 1.4.0. These two constructors
are provided to support the cause facility. The cause facility is
new in release 1.4. It is also known as the
chained exception facility.
(I won’t cover this facility in this lesson. Rather, I plan to cover it
in a series of lessons that I am developing having to do with the myriad of new
features in JDK 1.4.)
Methods of the Throwable class
Figure 2 shows some of the methods of the Throwable class. (I
omitted some of the methods introduced in JDK 1.4 for the reasons given above.)
fillInStackTrace() getStackTrace() printStackTrace(). setStackTrace(StackTraceElement[] stackTrace)
getLocalizedMessage() getMessage()
toString()
Figure 2
The StackTrace
The first four methods in Figure 2 deal with the StackTrace. In
case you are unfamiliar with the term StackTrace, this is a list of the
methods executed in sequence that led to the exception. (This is what
you typically see on the screen when your program aborts with a runtime error
that hasn’t been handled.)
Messages
The two methods dealing with messages provide access to a String
message that may be encapsulated in the exception object. The
getMessage class simply returns the message that was encapsulated when the
object was instantiated. (If no message was encapsulated, this method
returns null.)
The getLocalizedMessage method is a little more complicated to use.
According to Sun, «Subclasses may override this method in order to produce a
locale-specific message.»
The toString method
The toString method is inherited from the Object class and
overridden in the exception subclass to «return a short description of the
Throwable«.
Inherited methods
All exception objects inherit the methods of the Throwable class,
which are listed in Figure 2. Thus, any of these methods may be invoked by
the code in the catch block in its attempt to successfully handle the
exception.
For example, exceptions may have a message encapsulated in the exception
object, which can be accessed using the getMessage method. You can use
this to display a message describing the error or exception.
You can also use other methods of the Throwable class to:
- Display a stack trace showing where the exception or error occurred
- Produce a String representation of the exception object
So, what is an exception?
According to the online book entitled
The Java Tutorial by
Campione and Walrath:
«The term exception is shorthand for the phrase «exceptional event». It
can be defined as follows: Definition: An exception is an event that occurs
during the execution of a program that disrupts the normal flow of
instructions.»
When an exceptional condition occurs within a method, the method may
instantiate an exception object and hand it off to the runtime system to deal
with it. This is accomplished using the throw keyword.
(This is called throwing an exception.)
To be useful, the exception object should probably contain information about
the exception, including its type and the state of the program when the
exception occurred.
Handling the exception
At that point, the runtime system becomes responsible for finding a block of
code designed to handle the exception.
The runtime system begins its search with the method in which the exception
occurred and searches backwards through the call stack until it finds a method
that contains an appropriate exception handler (catch block).
An exception handler is appropriate if the type of the exception
thrown is the same as the type of exception handled by the handler, or is a
subclass of the type of exception handled by the handler.
Thus, the requirement to handle an exception that has been thrown progresses
up through the call stack until an appropriate handler is found to handle the
exception. If no appropriate handler is found, the runtime system and the
program terminate.
(If you have ever had a program terminate with a NullPointerException,
then you know how program termination works).
According to the jargon, the exception handler that is chosen is said to
catch the exception.
Advantages of using exception handling
According to Campione and Walrath, exception handling provides the following
advantages over «traditional» error management techniques:
- Separating Error Handling Code from «Regular» Code
- Propagating Errors Up the Call Stack
- Grouping Error Types and Error Differentiation
Separating error handling code from regular code
I don’t plan to discuss these advantages in detail. Rather, I will simply
refer you to The Java Tutorial and other good books where you can read
their discussions. However, I will comment briefly.
Campione and Walrath provide a good illustration where they show how a simple
program having about six lines of code get «bloated» into about 29 lines of very
confusing code through the use of traditional error management techniques. Not
only does the program suffer bloat, the logical flow of the original program
gets lost in the clutter of the modified program.
They then show how to accomplish the same error management using exception
handling. Although the version with exception handling contains about seventeen
lines of code, it is orderly and easy to understand. The additional lines of
code do not cause the original logic of the program to get lost.
You must still do the hard work
However, the use of exception handling does not spare you from the hard work
of detecting, reporting, and handling errors. What it does is provide a
means to separate the details of what to do when something out-of-the-ordinary
happens from the normal logical flow of the program code.
Propagating exceptions up the call stack
Sometimes it is desirable to propagate exception handling up the call stack
and let the corrective action be taken at a higher level.
For example, you might provide a class with methods that implement a stack.
One of the methods of your class might be to pop an element off the
stack.
What should your program do if a using program attempts to pop an element off
an empty stack? That decision might best be left to the user of your stack
class, and you might simply propagate the notification up to the calling method
and let that method take the corrective action.
Grouping exception types
When an exception is thrown, an object of one of the exception classes is
passed as a parameter. Objects are instances of classes, and classes fall
into an inheritance hierarchy in Java. Therefore, a natural hierarchy can
be created, which causes exceptions to be grouped in logical ways.
For example, going back to the stack example, you might create an exception
class that applies to all exceptional conditions associated with an object of
your stack class. Then you might extend that class into other classes that
pertain to specific exceptional conditions, such as push exceptions,
pop exceptions, and initialization exceptions.
When your code throws an exception object of a specific type, that object can
be caught by an exception handler designed either to:
- Catch on the basis of a group of exceptions, or
- Catch on the basis of a subgroup of that group, or
- Catch on the basis of one of the specialized exceptions.
In other words, an exception handler can catch exceptions of the class
specified by the type of its parameter, or can catch exceptions of any subclass
of the class specified by the type of its parameter.
More detailed information on exception handling
As explained earlier, except for Throwable objects of type Error
and for Throwable.Exception objects of type RuntimeException, Java
programs must either handle or declare all Exception
objects that are thrown. Otherwise, the compiler will refuse to compile
the program.
In other words, all exceptions other than those specified above are
checked by the compiler, and the compiler will refuse to compile the program
if the exceptions aren’t handled or declared. As a result, exceptions other than
those specified above are often referred to as checked exceptions.
Catching an exception
Just to make certain that we are using the same terminology, a method
catches an exception by providing an exception handler whose parameter type
is appropriate for that type of exception object. (I will more or less
use the terms catch block and exception handler interchangeably.)
The type of the parameter in the catch block must be the class from
which the exception was instantiated, or a superclass of that class that resides
somewhere between that class and the Throwable class in the inheritance
hierarchy.
Declaring an exception
If the code in a method can throw a checked exception, and the method does
not provide an exception handler for the type of exception object thrown, the
method must declare that it can throw that exception. The throws
keyword is used in the method declaration to declare that it throws an
exception of a particular type.
Any checked exception that can be thrown by a method is part of the method’s
programming interface (see the read method of the InputStream class,
which throws IOException, for example). Users of a method must
know about the exceptions that a method can throw in order to be able to handle
them. Thus, you must declare the exceptions that the method can throw in the
method signature.
Checked exceptions
Checked exceptions are all exception objects instantiated from subclasses of
the Exception class other than those of the RuntimeException
class.
Exceptions of all Exception subclasses other than RuntimeException
are checked by the compiler and will result in compiler errors if they are
neither caught nor declared.
You will learn how you can create your own exception classes later. Whether
your exception objects become checked or not depends on the class that you
extend when you define your exception class.
(If you extend a checked exception class, your new exception type will
be a checked exception. Otherwise, it will not be a checked exception.)
Exceptions that can be thrown within the scope of a
method
The exceptions that can be thrown within the scope of a method include not
only exceptions which are thrown by code written into the method, but also
includes exceptions thrown by methods called by that method, or methods called
by those methods, etc.
According to Campione and Walrath,
«This … includes any exception that can be thrown while the flow of
control remains within the method. Thus, this … includes both exceptions
that are thrown directly by the method with Java’s throw statement, and
exceptions that are thrown indirectly by the method through calls to other
methods.»
Sample programs
Now it’s time to take a look at some sample code designed to deal with
exceptions of the types delivered with the JDK. Initially I won’t include
exception classes that are designed for custom purposes. However, I will
deal with exceptions of those types later in the lesson.
The first three sample programs will illustrate the successive stages of
dealing with checked exceptions by either catching or declaring those
exceptions.
Sample program with no exception handling code
The first sample program shown in Listing 1 neither catches nor declares the
InterruptedException which can be thrown by the sleep method of
the Thread class.
/*File Excep11.java
Copyright 2002, R.G.Baldwin
Tested using JDK 1.4.0 under Win2000
**************************************/
import java.lang.Thread;
class Excep11{
public static void main(
String[] args){
Excep11 obj = new Excep11();
obj.myMethod();
}//end main
//---------------------------------//
void myMethod(){
Thread.currentThread().sleep(1000);
}//end myMethod
}//end class Excep11
Listing 1
A possible InterruptedException
The code in the main method of Listing 1 invokes the method named
myMethod. The method named myMethod invokes the method named
sleep of the Thread class. The method named sleep
declares that it throws InterruptedException.
InterruptedException is a checked exception. The program
illustrates the failure to either catch or declare InterruptedException
in the method named myMethod.
As a result, this program won’t compile. The compiler error is similar
to that shown in Figure 3. Note the caret in the last line that points to
the point where the compiler detected the problem.
unreported exception java.lang.InterruptedException; must be caught or declared to be thrown Thread.currentThread().sleep(1000); ^ Figure 3
As you can see, the compiler detected a problem where the sleep method
was called, because the method named myMethod failed to deal properly
with an exception that can be thrown by the sleep method.
Sample program that fixes one compiler error
The next version of the program, shown in Listing 2, fixes the problem
identified with the call to the sleep method, by declaring the exception
in the signature for the method named myMethod. The declaration of
the exception of type InterruptedException is highlighted in boldface in
Listing 2.
/*File Excep12.java
Copyright 2002, R.G.Baldwin
Tested using JDK 1.4.0 under Win2000
**************************************/
import java.lang.Thread;
class Excep12{
public static void main(
String[] args){
Excep12 obj = new Excep12();
obj.myMethod();
}//end main
//---------------------------------//
void myMethod()
throws InterruptedException{
Thread.currentThread().sleep(1000);
}//end myMethod
}//end class Excep12
Listing 2
Another possible InterruptedException
As was the case in the previous program, this program also illustrates a
failure to catch or declare an InterruptedException. However, in
this case, the problem has moved up one level in the call stack relative to the
problem with the program in Listing 1.
This program also fails to compile, producing a compiler error similar to
that shown in Figure 4. Note that the caret indicates that the problem is
associated with the call to myMethod.
unreported exception java.lang.InterruptedException; must be caught or declared to be thrown obj.myMethod(); ^ Figure 4
Didn’t solve the problem
Simply declaring a checked exception doesn’t solve the problem.
Ultimately, the exception must be handled if the compiler problem is to be
solved.
(Note, however, that it is possible to declare that the main
method throws a checked exception, which will cause the compiler to ignore it
and allow your program to compile.)
The program in Listing 2 eliminated the compiler error identified with the
call to the method named sleep. This was accomplished by declaring
that the method named myMethod throws InterruptedException.
However, this simply passed the exception up the call stack to the next
higher-level method in the stack. This didn’t solve the problem, it simply
handed it off to another method to solve.
The problem still exists, and is now identified with the call to myMethod
where it will have to be handled in order to make the compiler error go away.
Sample program that fixes the remaining compiler
error
The version of the program shown in Listing 3 fixes the remaining compiler
error. This program illustrates both declaring and handling a checked
exception. This program compiles and runs successfully.
/*File Excep13.java
Copyright 2002, R.G.Baldwin
Tested using JDK 1.4.0 under Win2000
**************************************/
import java.lang.Thread;
class Excep13{
public static void main(
String[] args){
Excep13 obj = new Excep13();
try{//begin try block
obj.myMethod();
}catch(InterruptedException e){
System.out.println(
"Handle exception here");
}//end catch block
}//end main
//---------------------------------//
void myMethod()
throws InterruptedException{
Thread.currentThread().sleep(1000);
}//end myMethod
}//end class Excep13
Listing 3
The solution to the problem
This solution to the problem is accomplished by surrounding the call to
myMethod with a try block, which is followed immediately by an
appropriate catch block. In this case, an appropriate catch
block is one whose parameter type is either InterruptedException, or a
superclass of InterruptedException.
(Note, however, that the superclass cannot be higher than the
Throwable class in the inheritance hierarchy.)
The myMethod method declares the exception
As in the previous version, the method named myMethod (declares the
exception and passes it up the call stack to the method from which it was
called.
The main method handles the exception
In the new version shown in Listing 3, the main method provides a
try block with an appropriate catch block for dealing
with the problem (although it doesn’t actually deal with it in any
significant way). This can be interpreted as follows:
- Try to execute the code within the try block.
- If an exception occurs, search for a catch block that matches the
type of object thrown by the exception. - If such a catch block can be found, immediately transfer control to
the catch block without executing any of the remaining code in the try
block. (For simplicity, this program didn’t have any remaining code.
Some later sample programs will illustrate code being skipped due to the
occurrence of an exception.)
Not a method call
Note that this transfer of control is not a method call. It is an
unconditional transfer of control. There is no return from a catch block.
Matching catch block was found
In this case, there was a matching catch block to receive control. In
the event that an InterruptedException is thrown, the program would
execute the statement within the body of the catch block, and then
transfer control to the code following the final catch block in the group
of catch blocks (in this case, there was only one catch block).
No output is produced
It is unlikely that you will see any output when you run this program,
because it is unlikely that an InterruptedException will be thrown. (I
didn’t provide any code that will cause such an exception to occur.)
A sample program that throws an exception
Now let’s look at the sample program in Listing 4, which throws an exception
and deals with it. This program illustrates the implementation of
exception handling using the try/catch block structure.
/*File Excep14.java
Copyright 2002, R. G. Baldwin
Tested with JDK 1.4.0 under Win2000
**************************************/
class Excep14{
public static void main(
String[] args){
try{
for(int cnt = 2; cnt >-1; cnt--){
System.out.println(
"Running. Quotient is: "
+ 6/cnt);
}//end for-loop
}//end try block
catch(ArithmeticException e){
System.out.println(
"Exception message is: "
+ e.getMessage()
+ "nStacktrace shows:");
e.printStackTrace();
System.out.println(
"String representation isn " +
e.toString());
System.out.println(
"Put corrective action here");
}//end catch block
System.out.println(
"Out of catch block");
}//end main
}//end class Excep14
Listing 4
Keeping it simple
I try to keep my sample programs as simple as possible, introducing the
minimum amount of complexity necessary to illustrate the main point of the
program. It is easy to write a really
simple program that throws an unchecked ArithmeticException.
Therefore, the program in Listing 4 was written to throw an
ArithmeticException. This was accomplished by trying to perform an
integer divide by zero.
The try/catch structure is the same …
It is important to note that the try/catch structure illustrated in Listing 4
would be the same whether the exception is checked or unchecked. The main
difference is that you are not required by the compiler to handle unchecked
exceptions and you are required by the compiler to either handle or declare
checked exceptions.
Throwing an ArithmeticException
The code in Listing 4 executes a simple counting loop inside a try
block. During each iteration, the counting loop divides the integer 6 by
the value of the counter. When the value of the counter goes to zero, the
runtime system tries to perform an integer divide by zero operation, which
causes it to throw an ArithmeticException.
Transfer control immediately
At that point, control is transferred directly to the catch block that
follows the try block. This is an appropriate catch
block because the type of parameter declared for the catch block is
ArithmeticException. It matches the type of the object that is thrown.
(It would also be appropriate if the declared type of the parameter were
a superclass of ArithmeticException, up to and including the class
named Throwable. Throwable is a direct subclass of
Object. If you were to declare the parameter type for the catch
block as Object, the compiler would produce an incompatible type
error.)
Invoking methods inside the catch block
Once control enters the catch block, three of the methods of the
Throwable class are invoked to cause information about the situation to be
displayed on the screen. The output produced by the program is similar to
that shown in Figure 5.
Running. Quotient is: 3 Running. Quotient is: 6 Exception message is: / by zero Stacktrace shows: java.lang.ArithmeticException: / by zero at Excep14.main(Excep14.java:35) String representation is java.lang.ArithmeticException: / by zero Put corrective action here Out of catch block Figure 5
Key things to note
The key things to note about the program in Listing 5 are:
- The code to be protected is contained in a try block.
- The try block is followed immediately by an appropriate catch
block. - When an exception is thrown within the try block, control is
transferred immediately to the catch block with the matching or
appropriate parameter type. - Although the code in the catch block simply displays the current
state of the program, it could contain code that attempts to rectify the
problem. - Once the code in the catch block finishes executing, control is
passed to the next executable statement following the catch block,
which in this program is a print statement.
Doesn’t attempt to rectify the problem
This program doesn’t attempt to show how an actual program might recover from
an exception of this sort. However, it is clear that (rather than
experiencing automatic and unconditional termination) the program remains in
control, and in some cases, recovery might be possible.
This sample program illustrates try and catch. The use of
finally, will be discussed and illustrated later.
A nuisance problem explained
While we are at it, I would be remiss in failing to mention a nuisance
problem associated with exception handling.
As you may recall, the scope of a variable in Java is limited to the block of
code in which it is declared. A block is determined by enclosing code within a
pair of matching braces: {…}.
Since a pair of braces is required to define a try block, the scope of
any variables or objects declared inside the try block is limited
to the try block.
While this is not an insurmountable problem, it may require you to modify
your programming style in ways that you find distasteful. In particular,
if you need to access a variable both within and outside the try block,
you must declare it before entering the try block.
The process in more detail
Now that you have seen some sample programs to help you visualize the
process, lets discuss the process in more detail.
The try block
According to Campione and Walrath,
«The first step in writing any exception handler is putting the Java
statements within which an exception can occur into a try block. The try block
is said to govern the statements enclosed within it and defines the scope of
any exception handlers (established by subsequent catch blocks) associated
with it.»
Note that the terminology being used by Campione and Walrath treats the
catch block as the «exception handler» and treats the try
block as something that precedes one or more exception handlers. I don’t
disagree with their terminology. I mention it only for the purpose of avoiding
confusion over terminology.
The syntax of a try block
The general syntax of a try block, as you saw in the previous program,
has the keyword try followed by one or more statements enclosed in
a pair of matching braces, as shown in Figure 6.
try{ //java statements }//end try block Figure 6
Single statement and multiple exceptions
You may have more than one statement that can throw one or more exceptions
and you will need to deal with all of them.
You could put each such statement that might throw exceptions within its own
try block and provide separate exception handlers for each try
block.
(Note that some statements, particularly those that invoke other
methods, could potentially throw many different types of exceptions.)
Thus a try block consisting of a single statement might require many
different exception handlers or catch blocks following it.
Multiple statements and multiple exceptions
You could put all or several of the statements that might throw exceptions
within a single try block and associate multiple exception handlers with
it. There are a number of practical issues involved here, and only you can
decide in any particular instance which approach would be best.
The catch blocks must follow the try block
However you decide to do it, the exception handlers associated with a try
block must be placed immediately following their associated try block. If
an exception occurs within the try block, that exception is
handled by the appropriate exception handler associated with the try
block. If there is no appropriate exception handler associated with the
try block, the system attempts to find an appropriate exception handler in
the next method up the call stack.
A try block must be accompanied by at least one catch block
(or one finally block). Otherwise, a compiler error that reads
something like ‘try’ without ‘catch’ or ‘finally’ will occur.
The catch block(s)
Continuing with what Campione and Walrath have to say:
«Next, you associate exception handlers with a try block by providing
one or more catch blocks directly after the try block.»
There can be no intervening code between the end of the try block and
the beginning of the first catch block, and no intervening code
between catch blocks.
Syntax of a catch block
The general form of a catch block is shown in Figure 7.
catch(ThrowableObjectType paramName){ //Java statements to handle the // exception }//end catch block Figure 7
The declaration for the catch block requires a single argument as
shown. The syntax for the argument declaration is the same as an argument
declaration for a method.
Argument type specifies type of matching exception
object
The argument type declares the type of exception object that a particular
catch block can handle. The type must be Throwable, or a
subclass of the Throwable class discussed earlier.
A parameter provides the local name
Also, as in a method declaration, there is a parameter, which is the name by
which the handler can refer to the exception object. For example, in an
earlier program, I used statements such as e.getMessage()to
access an instance method of an exception object caught by the exception
handler. In that case, the name of the parameter was e.
You access the instance variables and methods of exception objects the same
way that you access the instance variables and methods of other objects.
Proper order of catch blocks
According to Campione and Walrath:
«The catch block contains a series of legal Java statements. These
statements are executed if and when the exception handler is invoked. The
runtime system invokes the exception handler when the handler is the first one
in the call stack whose type matches that of the exception thrown.»
Therefore, the order of your exception handlers is very important,
particularly if you have some handlers, which are further up the exception
hierarchy than others.
Those handlers that are designed to handle exception types furthermost from
the root of the hierarchy tree (Throwable) should be placed first
in the list of exception handlers.
Otherwise, an exception handler designed to handle a specific type of object
may be preempted by another handler whose exception type is a superclass of that
type, if the superclass exception handler appears earlier in the list of
exception handlers.
Catching multiple exception types with one handler
Exception handlers that you write may be more or less specialized. In
addition to writing handlers for very specialized exception objects, the Java
language allows you to write general exception handlers that handle multiple
types of exceptions.
Java exceptions are Throwable objects (instances of the
Throwable class or a subclass of the Throwable class).
The Java standard library contains numerous classes that are subclasses of
Throwable and thus build a hierarchy of Throwable classes.
According to Campione and Walrath:
«Your exception handler can be written to handle any class that inherits
from Throwable. If you write a handler for a «leaf» class (a class with
no subclasses), you’ve written a specialized handler: it will only handle
exceptions of that specific type. If you write a handler for a «node» class (a
class with subclasses), you’ve written a general handler: it will handle any
exception whose type is the node class or any of its subclasses.»
You have a choice
Therefore, when writing exception handlers, you have a choice. You can
write a handler whose exception type corresponds to a node in the inheritance
hierarchy, and it will be appropriate to catch exceptions of that type,
or any subclass of that type.
Alternately, you can write a handler whose exception type corresponds to a
leaf, in which case, it will be appropriate to catch exceptions of
that type only.
And finally, you can mix and match, writing some exception handlers whose
type corresponds to a node, and other exception handlers whose type corresponds
to a leaf. In all cases, however, be sure to position your exception
handlers in reverse subclass order, with the furthermost subclass from the root
appearing first, and the root class appearing last.
The finally block
And finally (no pun intended), Campione and Walrath tell us:
«Java’s finally block provides a mechanism that allows your method to
clean up after itself regardless of what happens within the try block. Use the
finally block to close files or release other system resources.»
To elaborate, the finally block can be used to provide a mechanism for
cleaning up open files, etc., before allowing control to be passed to a
different part of the program. You accomplish this by writing the cleanup
code within a finally block.
Code in finally block is always executed
It is important to remember that the runtime system always executes the code
within the finally block regardless of what happens within the try
block.
If no exceptions are thrown, none of the code in catch blocks is
executed, but the code in the finally block is executed.
If an exception is thrown and the code in an exception handler is executed,
once the execution of that code is complete, control is passed to the finally
block and the code in the finally block is executed.
(There is one important exception to the above. If the code in the
catch block terminates the program by executing System.exit(0),
the code in the finally block will not be executed.)
The power of the finally block
The sample program shown in Listing 5 illustrates the power of the finally
block.
/*File Excep15.java
Copyright 2002, R. G. Baldwin
Tested with JDK 1.4.0 under Win2000
**************************************/
class Excep15{
public static void main(
String[] args){
new Excep15().aMethod();
}//end main
//---------------------------------//
void aMethod(){
try{
int x = 5/0;
}//end try block
catch(ArithmeticException e){
System.out.println(
"In catch, terminating aMethod");
return;
}//end catch block
finally{
System.out.println(
"Executing finally block");
}//end finally block
System.out.println(
"Out of catch block");
}//end aMethod
}//end class Excep15
Listing 5
Execute return statement in catch block
The code in Listing 5 forces an ArithmeticException by attempting to
do an integer divide by zero. Control is immediately transferred to the
matching catch block, which prints a message and then executes a
return statement.
Normally, execution of a return statement terminates the method
immediately. In this case, however, before the method terminates and
returns control to the calling method, the code in the finally block is
executed. Then control is transferred to the main method, which
called this method in the first place.
Figure 8 shows the output produced by this program.
In catch, terminating aMethod Executing finally block Figure 8
This program demonstrates that the finally block really does have the final
word.
Declaring exceptions thrown by a method
Sometimes it is better to handle exceptions in the method in which they are
detected, and sometimes it is better to pass them up the call stack and let
another method handle them.
In order to pass exceptions up the call stack, you must declare them
in your method signature.
To declare that a method throws one or more exceptions, you add a
throws clause to the method signature for the method. The throws
clause is composed of the throws keyword followed by a
comma-separated list of all the exceptions thrown by that method.
The throws clause goes after the method name and argument list and
before the curly bracket that defines the scope of the method.
Figure 9 shows the syntax for declaring that a method throws four
different types of exceptions.
void myMethod() throws InterruptedException, MyException, HerException, UrException { //method code }//end myMethod() Figure 9
Assuming that these are checked exceptions, any method calling this method
would be required to either handle these exception types, or continue passing
them up the call stack. Eventually, some method must handle them or the program
won’t compile.
(Note however that while it might not represent good programming
practice, it is allowable to declare that the main method throws
exceptions. This is a way to avoid handling checked exceptions and still
get your program to compile.)
The throw keyword
Before your code can catch an exception, some Java code must throw
one. The exception can be thrown by code that you write, or by code that you are
using that was written by someone else.
Regardless of who wrote the code that throws the exception, it’s always
thrown with the Java throw keyword. At least that is true
for exceptions that are thrown by code written in the Java language.
(Exceptions such as ArithmeticException are also thrown by the
runtime system, which is probably not written using Java source code.)
A single argument is required
When formed into a statement, the throw keyword requires a single
argument, which must be a reference to an object instantiated from the
Throwable class, or any subclass of the Throwable class. Figure
10 shows an example of such a statement.
throw new myThrowableClass("Message"); Figure 10
If you attempt to throw an object that is not instantiated from Throwable
or one of its subclasses, the compiler will refuse to compile your program.
Defining your own exception classes
Now you know how to write exception handlers for those exception objects that
are thrown by the runtime system, and thrown by methods in the standard class
library.
It is also possible for you to define your own exception classes, and to
cause objects of those classes to be thrown whenever an exception occurs.
In this case, you get to decide just what constitutes an exceptional condition.
For example, you could write a data-processing application that processes
integer data obtained via a TCP/IP link from another computer. If the
specification for the program indicates that the integer value 10 should never
be received, you could use an occurrence of the integer value 10 to cause an
exception object of your own design to be thrown.
Choosing the exception type to throw
Before throwing an exception, you must decide on its type. Basically,
you have two choices in this regard:
- Use an exception class written by someone else, such as the myriad of
exception classes defined in the Java standard library. - Define an exception class of your own.
An important question
So, an important question is, when should you define your own exception
classes and when should you use classes that are already available.
Because this is only one of many design issues, I’m not going to try to give you
a ready answer to the question. However, I will refer you to
The Java
Tutorial by Campione and Walrath where you will find a checklist to help you
make this decision.
Choosing a superclass to extend
If you decide to define your own exception class, it must be a subclass of
Throwable. You must decide which class you will extend.
The two existing subclasses of Throwable are Exception and
Error. Given the earlier description of Error and its subclasses, it
is not likely that your exceptions would fit the Error category. (In
concept, errors are reserved for serious hard errors that occur deep within the
system.)
Checked or unchecked exception
Therefore, your new class should probably be a subclass of Exception.
If you make it a subclass of RuntimeException, it won’t be a checked
exception. If you make it a subclass of Exception, but not a
subclass of RuntimeException, it will be a checked exception.
Only you can decide how far down the Exception hierarchy you want to
go before creating a new branch of exception classes that are unique to your
application.
Naming conventions
Many Java programmers append the word Exception to the end of all class names
that are subclasses of Exception, and append the word Error to the end of
all class names that are subclasses of Error.
One more sample program
Let’s wrap up this lesson with one more sample program named Excep16.
We will define our own exception class in this program. Then we will throw,
catch and process an exception object instantiated from that class.
Discuss in fragments
This program is a little longer than the previous programs, so I will break
it down and discuss it in fragments. A complete listing of the program is
shown in Listing 10.
The class definition shown in Listing 6 is used to construct a custom
exception object that encapsulates a message. Note that this class extends
Exception. (Therefore, it is a checked exception.)
class MyException extends Exception{
MyException(String message){//constr
super(message);
}//end constructor
}//end MyException class
Listing 6
The constructor for this class receives an incoming String message
parameter and passes it to the constructor for the superclass. This makes
the message available for access by the getMessage method invoked in the
catch block.
The try block
Listing 7 shows the beginning of the main method, including the entire
try block
class Excep16{//controlling class
public static void main(
String[] args){
try{
for(int cnt = 0; cnt < 5; cnt++){
//Throw a custom exception, and
// pass message when cnt == 3
if(cnt == 3) throw
new MyException("3");
//Transfer control before
// processing for cnt == 3
System.out.println(
"Processing data for cnt = "
+ cnt);
}//end for-loop
}//end try block
Listing 7
The main method executes a for loop (inside the try
block) that guarantees that the variable named cnt will reach a value
of 3 after a couple of iterations.
Once during each iteration, (until the value of cnt reaches 3)
a print statement inside the for loop displays the value of cnt.
This results in the output shown in Figure 11.
Processing data for cnt = 0 Processing data for cnt = 1 Processing data for cnt = 2 Figure 11
What happens when cnt equals 3?
However, when the value of cnt equals 3, the throw statement
highlighted in boldface in Listing 7 is executed. This causes control to
transfer immediately to the matching catch block following the try
block (see Listing 8). During this iteration, the print statement
following the throw statement is not executed. Therefore, the
output never shows a value for cnt greater than 2, as shown in Figure 11.
The catch block
Listing 8 shows a catch block whose type matches the type of exception
thrown in Listing 7.
catch(MyException e){
System.out.println(
"In exception handler, "
+ "get the messagen"
+ e.getMessage());
}//end catch block
Listing 8
When the throw statement is executed in Listing 7, control is
transferred immediately to the catch block in Listing 8. No further
code is executed within the try block.
A reference to the object instantiated as the argument to the throw
keyword in Listing 7 is passed as a parameter to the catch block.
That reference is known locally by the name e inside the catch
block.
Using the incoming parameter
The code in the catch block invokes the method named getMessage
(inherited from the Throwable class) on the incoming parameter and
displays that message on the screen. This produces the output shown in
Figure 12.
In exception handler, get the message 3 Figure 12
When the catch block finishes execution …
When the code in the catch block has completed execution, control is
transferred to the first executable statement following the catch block
as shown in Listing 9.
System.out.println(
"Out of catch block");
}//end main
}//end class Excep16
Listing 9
That executable statement is a print statement that produces the output shown
in Figure 13.
Out of catch block Figure 13
A complete listing of the program is shown in Listing 10.
/*File Excep16.java
Copyright 2002, R. G. Baldwin
Illustrates defining, throwing,
catching, and processing a custom
exception object that contains a
message.
Tested using JDK 1.4.0 under Win 2000
The output is:
Processing data for cnt = 0
Processing data for cnt = 1
Processing data for cnt = 2
In exception handler, get the message
3
Out of catch block
**************************************/
//The following class is used to
// construct a customized exception
// object containing a message
class MyException extends Exception{
MyException(String message){//constr
super(message);
}//end constructor
}//end MyException class
//===================================//
class Excep16{//controlling class
public static void main(
String[] args){
try{
for(int cnt = 0; cnt < 5; cnt++){
//Throw a custom exception, and
// pass message when cnt == 3
if(cnt == 3) throw
new MyException("3");
//Transfer control before
// processing for cnt == 3
System.out.println(
"Processing data for cnt = "
+ cnt);
}//end for-loop
}//end try block
catch(MyException e){
System.out.println(
"In exception handler, "
+ "get the messagen"
+ e.getMessage());
}//end catch block
//-------------------------------//
System.out.println(
"Out of catch block");
}//end main
Listing 10
Summary
This lesson has covered many of the details having to do with exception
handling in Java. By now, you should know that the use of exception
handling is not optional in Java, and you should have a pretty good idea how to
use exception handling in a beneficial way.
Along the way, the discussion has included the following topics:
- What is an exception?
- How do you throw and catch exceptions?
- What do you do with an exception once you have caught it?
- How do you make use of the exception class hierarchy provided by the Java
development environment?
What’s Next?
For the time being, that completes the miniseries entitled «The Essence of
OOP using Java.» I may decide to come back later and add some lessons
on inner classes and other similar topics, but it will probably be a while
before I get around to that. In the meantime, I sincerely hope that you
have enjoyed this miniseries, and have found the lessons useful in your
continuing effort to learn and understand OOP as implemented using Java.
Copyright 2002, Richard G. Baldwin. Reproduction in whole or in part in
any form or medium without express written permission from Richard Baldwin is
prohibited.
About the author
Richard Baldwin
is a college professor (at Austin Community College in Austin, Texas) and
private consultant whose primary focus is a combination of Java, C#, and
XML. In addition to the many platform and/or language independent benefits
of Java and C# applications, he believes that a combination of Java, C#,
and XML will become the primary driving force in the delivery of structured
information on the Web.
Richard has participated in numerous consulting projects, and he
frequently provides onsite training at the high-tech companies located
in and around Austin, Texas. He is the author of Baldwin’s Programming
Tutorials,
which has gained a worldwide following among experienced and aspiring programmers.
He has also published articles in JavaPro magazine.
Richard holds an MSEE degree from Southern Methodist University and
has many years of experience in the application of computer technology
to real-world problems.
[email protected]
-end-
30.12.2019Java
Типы исключений в Java
Встроенные исключения — это исключения, доступные в библиотеках Java. Эти исключения подходят для объяснения определенных ошибок. Ниже приведен список важных встроенных исключений в Java.
Примеры встроенных исключений:
- Арифметическое исключение: оно генерируется, когда в арифметической операции возникло исключительное условие.
class
ArithmeticException_Demo {
public
static
void
main(String args[])
{
try
{
int
a =
30
, b =
0
;
int
c = a / b;
System.out.println(
"Result = "
+ c);
}
catch
(ArithmeticException e) {
System.out.println(
"Can't divide a number by 0"
);
}
}
}
Выход:
Can't divide a number by 0
- ArrayIndexOutOfBounds Исключение: выдается для указания на доступ к массиву с недопустимым индексом. Индекс либо отрицательный, либо больше или равен размеру массива.
class
ArrayIndexOutOfBound_Demo {
public
static
void
main(String args[])
{
try
{
int
a[] =
new
int
[
5
];
a[
6
] =
9
;
}
catch
(ArrayIndexOutOfBoundsException e) {
System.out.println(
"Array Index is Out Of Bounds"
);
}
}
}
Выход:
Array Index is Out Of Bounds
- ClassNotFoundException: это исключение возникает, когда мы пытаемся получить доступ к классу, определение которого не найдено.
class
Bishal {
}
class
Geeks {
}
class
MyClass {
public
static
void
main(String[] args)
{
Object o =
class
.forName(args[
0
]).newInstance();
System.out.println(
"Class created for"
+ o.getClass().getName());
}
}
Выход:
ClassNotFoundException
- FileNotFoundException: это исключение возникает, когда файл недоступен или не открывается.
import
java.io.File;
import
java.io.FileNotFoundException;
import
java.io.FileReader;
class
File_notFound_Demo {
public
static
void
main(String args[])
{
try
{
File file =
new
File(
"E:// file.txt"
);
FileReader fr =
new
FileReader(file);
}
catch
(FileNotFoundException e) {
System.out.println(
"File does not exist"
);
}
}
}
Выход:
File does not exist
- IOException: это бросается, когда операция ввода-вывода потерпела неудачу или прервалась
import
java.io.*;
class
Geeks {
public
static
void
main(String args[])
{
FileInputStream f =
null
;
f =
new
FileInputStream(
"abc.txt"
);
int
i;
while
((i = f.read()) != -
1
) {
System.out.print((
char
)i);
}
f.close();
}
}
Выход:
error: unreported exception IOException; must be caught or declared to be thrown
- InterruptedException: он генерируется, когда поток ожидает, спит или выполняет некоторую обработку, и прерывается.
class
Geeks {
public
static
void
main(String args[])
{
Thread t =
new
Thread();
t.sleep(
10000
);
}
}
Выход:
error: unreported exception InterruptedException; must be caught or declared to be thrown
- NoSuchMethodException: t выбрасывается при доступе к методу, который не найден.
class
Geeks {
public
Geeks()
{
Class i;
try
{
i = Class.forName(
"java.lang.String"
);
try
{
Class[] p =
new
Class[
5
];
}
catch
(SecurityException e) {
e.printStackTrace();
}
catch
(NoSuchMethodException e) {
e.printStackTrace();
}
}
catch
(ClassNotFoundException e) {
e.printStackTrace();
}
}
public
static
void
main(String[] args)
{
new
Geeks();
}
}
Выход:
error: exception NoSuchMethodException is never thrown in body of corresponding try statement
- NullPointerException: это исключение возникает при обращении к членам нулевого объекта. Null ничего не представляет
class
NullPointer_Demo {
public
static
void
main(String args[])
{
try
{
String a =
null
;
System.out.println(a.charAt(
0
));
}
catch
(NullPointerException e) {
System.out.println(
"NullPointerException.."
);
}
}
}
Выход:
NullPointerException..
- NumberFormatException: это исключение возникает, когда метод не может преобразовать строку в числовой формат.
class
NumberFormat_Demo {
public
static
void
main(String args[])
{
try
{
int
num = Integer.parseInt(
"akki"
);
System.out.println(num);
}
catch
(NumberFormatException e) {
System.out.println(
"Number format exception"
);
}
}
}
Выход:
Number format exception
- StringIndexOutOfBoundsException: он вызывается методами класса String, чтобы указать, что индекс либо отрицателен, чем размер строки.
class
StringIndexOutOfBound_Demo {
public
static
void
main(String args[])
{
try
{
String a =
"This is like chipping "
;
char
c = a.charAt(
24
);
System.out.println(c);
}
catch
(StringIndexOutOfBoundsException e) {
System.out.println(
"StringIndexOutOfBoundsException"
);
}
}
}
Выход:
StringIndexOutOfBoundsException
Некоторые другие важные исключения
- ClassCastException
class
Test {
public
static
void
main(String[] args)
{
String s =
new
String(
"Geeks"
);
Object o = (Object)s;
Object o1 =
new
Object();
String s1 = (String)o1;
}
}
Выход:
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String
- StackOverflowError
class
Test {
public
static
void
main(String[] args)
{
m1();
}
public
static
void
m1()
{
m2();
}
public
static
void
m2()
{
m1();
}
}
Выход:
Exception in thread "main" java.lang.StackOverflowError
- NoClassDefFoundError
class
Test
{
public
static
void
main(String[] args)
{
System.out.println(
"HELLO GEEKS"
);
}
}
Выход:
Note: If the corresponding Test.class file is not found during compilation then we will get Run-time Exception saying Exception in thread "main" java.lang.NoClassDefFoundError
- ExceptionInInitializerError
Код 1:class
Test {
static
int
x =
10
/
0
;
public
static
void
main(String[] args)
{
}
}
Выход:
Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.ArithmeticException: / by zero
Код 2:
class
Test {
static
{
String s =
null
;
System.out.println(s.length());
}
public
static
void
main(String[] args)
{
}
}
Выход:
Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.NullPointerException
Объяснение: Вышеуказанное исключение возникает всякий раз, когда выполняется статическое присвоение переменной и статический блок, если возникает какое-либо исключение.
- IllegalArgumentException
class
Test {
public
static
void
main(String[] args)
{
Thread t =
new
Thread();
Thread t1 =
new
Thread();
t.setPriority(
7
);
t1.setPriority(
17
);
}
}
Выход:
Exception in thread "main" java.lang.IllegalArgumentException
Объяснение: Исключение возникает явно либо программистом, либо разработчиком API, чтобы указать, что метод был вызван с недопустимым аргументом.
- IllegalArgumentException
class
Test {
public
static
void
main(String[] args)
{
Thread t =
new
Thread();
t.start();
t.start();
}
}
Выход:
Exception in thread "main" java.lang.IllegalThreadStateException
Объяснение: Вышеуказанное исключение явно возникает либо программистом, либо разработчиком API, чтобы указать, что метод был вызван в неправильное время.
- AssertionError
class
Test {
public
static
void
main(String[] args)
{
assert
(x >=
10
);
}
}
Выход:
Exception in thread "main" java.lang.AssertionError
Объяснение: Вышеуказанное исключение явно вызывается программистом или разработчиком API, чтобы указать, что утверждение assert не выполнено.
Эта статья предоставлена Бишал Кумар Дубей . Если вы как GeeksforGeeks и хотели бы внести свой вклад, вы также можете написать статью с помощью contribute.geeksforgeeks.org или по почте статьи contribute@geeksforgeeks.org. Смотрите свою статью, появляющуюся на главной странице GeeksforGeeks, и помогите другим вундеркиндам.
Пожалуйста, пишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по обсуждаемой выше теме.
Рекомендуемые посты:
- Исключения в Java
- Связанные исключения в Java
- Ошибки V / S Исключения в Java
- Проверено против непроверенных исключений в Java
- Использование throw, catch и instanceof для обработки исключений в Java
- Java.util.LinkedList.poll (), pollFirst (), pollLast () с примерами на Java
- Java.lang.Short toString () метод в Java с примерами
- Java.util.Collections.rotate () Метод в Java с примерами
- Java lang.Long.byteValue () метод в Java с примерами
- Класс Java.util.concurrent.RecursiveAction в Java с примерами
- Java.util.function.DoublePredicate интерфейс в Java с примерами
- Java.util.function.LongPredicate интерфейс в Java с примерами
- Класс Java.util.concurrent.RecursiveTask в Java с примерами
- Java lang.Long.reverse () метод в Java с примерами
- Java.util.function.IntPredicate интерфейс в Java с примерами
Встроенные исключения в Java с примерами
0.00 (0%) 0 votes
Exception in the unwanted unexpected event that disturbs the normal flow of the program is called an exception.
Example:
SleepingException
TyrePunchuredException
FileNotFoundException …etc.
It is highly recommended to handle exceptions. The main objective of exception handling is graceful (normal) termination of the program.
What is the meaning of exception handling?
Exception handling doesn’t mean repairing an exception. We have to define alternative ways to continue the rest of the program normally this way of «defining alternative is nothing but exception handling».
Example
Suppose our programming requirement is to read data from remote file locating at London at runtime if London file is not available our program should not be terminated abnormally.
We have to provide a local file to continue the rest of the program normally. This way of defining alternative is nothing but exception handling.
Example:
Try
{
read data from london file
}
catch(FileNotFoundException e)
{
use local file and continue rest of the program normally
}
}
.
.
.
Runtime stack mechanism
For every thread, JVM will create a separate stack all method calls performed by the thread will be stored in that stack.
Each entry in the stack is called «one activation record» (or) «stack frame».
After completing every method call JVM removes the corresponding entry from the stack.
After completing all method calls JVM destroys the empty stack and terminates the program normally.
class Test { public static void main(String[] args){ doStuff(); } public static void doStuff(){ doMoreStuff(); } public static void doMoreStuff(){ System.out.println("Hello"); }} Output: Hello
Example:
1) If an exception raised inside any method then the method is responsible to create an Exception object with the following information.
2) Name of the exception.
3) Description of the exception.
4) Location of the exception. (StackTrace)
After creating that Exception object the method handovers that object to the JVM.
JVM checks whether the method contains any exception handling code or not.
5) If the method won’t contain any handling code then JVM terminates that method abnormally and removes corresponding entry form the stack.
6) JVM identifies the caller method and checks whether the caller method contains any handling code or not. If the caller method also does not contain handling code then JVM terminates that caller also abnormally and the removes corresponding entry from the stack.
7) This process will be continued until the main() method and if the main() method also doesn’t contain any exception handling code then JVM terminates main() method and removes the corresponding entry from the stack.
Then JVM handovers the responsibility of exception handling to the default exception handler.
9) The default exception handler just prints exception information to the console in the following formats and terminates the program abnormally.
Name of exception: description
Location of exception (stack trace)
class Test { public static void main(String[] args){ doStuff(); } public static void doStuff(){ doMoreStuff(); } public static void doMoreStuff(){ System.out.println(10/0); }} Output: Runtime error Exception in thread "main" java.lang.ArithmeticException: / by zero at Test.doMoreStuff(Test.java:10) at Test.doStuff(Test.java:7) at Test.main(Test.java:4)
Example:
Diagram
Exception hierarchy
Throwable acts as a root for exception hierarchy. The throwable class contains the following two child classes.
Exception:
Most of the cases exceptions are caused by our program and these are recoverable.
Ex: If FileNotFoundException occurs we can use a local file and we can continue the rest of the program execution normally.
Error:
Most of the cases errors are not caused by our program these are due to lack of system resources and these are non-recoverable.
Ex: If OutOfMemoryError occurs being a programmer we can’t do anything the program will be terminated abnormally.
System Admin or Server Admin is responsible to raise/increase heap memory.
Checked Vs Unchecked Exceptions
There are 2 types of exception:
- Checked : The exceptions which are checked by the compiler for smooth execution of the program at runtime are called checked exceptions.
- 1)HallTicketMissingException
- 2)PenNotWorkingException
- 3)FileNotFoundException
-
Un Checked
: The exceptions which are not checked by the compiler are called unchecked exceptions. - 1)BombBlaustException
- 2)ArithmeticException
- 3)NullPointerException.
Note: RuntimeException and its child classes, Error, and its child classes are unchecked and all the remaining are considered as checked exceptions.
Note: Whether exception is checked or unchecked compulsory it should occur at runtime only there is no chance of occurring any exception at compile time.
Partially checked Vs fully checked :
A checked exception is said to be fully checked if and only if all its child classes are also checked.
Example:
1) IOException
2) InterruptedException
A checked exception is said to be partially checked if and only if some of its child classes are unchecked.
Example:
Exception The only partially checked exceptions available in java are :
1) Throwable.
2) Exception.
Which of the following are checked?
RuntimeException——unchecked
Error——unchecked
IOException——fully checked
Exception——partially checked
InterruptedException——fully checked
Throwable——partially checked
ArithmeticException —— unchecked Checked
NullPointerException —— unchecked
FileNotFoundException —— fully checked
Diagram:

Customized exception handling by try-catch
1) It is highly recommended to handle exceptions.
2) In our program the code which may cause an exception is called risky code, we have to place risky code inside try block and the corresponding handling code inside the catch block.
Example:
Try
{
risky code
}
catch(Exception e)
{
handling code
}
Without try-catch
Example: class Test { public static void main(String[] args){ System.out.println("statement1"); System.out.println(10/0); System.out.println("statement3"); } } output: statement1 RE:AE:/by zero at Test.main() Abnormal termination
With try-catch
class Test { public static void main(String[] args){ System.out.println("statement1"); try{ System.out.println(10/0); } catch(ArithmeticException e){ System.out.println(10/2); } System.out.println("statement3"); }} Output: statement1 5 statement3 Normal termination.
Example:
Control flow in try-catch
try{ statement1; statement2; statement3; } catch(X e) { statement4; } statement5; Output: statement1 5 statement3 Normal termination. . . .
- Case 1: There is no exception.
1, 2, 3, 5 normal terminations.
Case 2: if an exception raised at statement 2 and corresponding catch block matched 1, 4, 5 normal terminations.
Case 3:
if an exception raised at statement 2 but the corresponding catch block not matched, 1 followed by abnormal termination.
Case 4:
if an exception raised at statement 4 or statement 5 then it’s always abnormal termination of the program.
Note:
1) Within the try block if anywhere an exception raised then the rest of the try block won’t be executed even though we handled that exception. Hence we have to place/take only risk code inside try and length of the try block should be as less as possible.
2) If any statement raises an exception and it is not part of any try block then it is always abnormal termination of the program.
3) There may be a chance of raising an exception inside catch and finally blocks also in addition to try block.
Various methods to print exception information:
The Throwable class defines the following methods to print exception information to the console.
printStackTrace()
This method prints exception information in the following format.
Name of the exception: description of the exception
Stack trace
toString():
This method prints exception information in the following format.
Name of the exception: description of the exception
getMessage():
This method returns only a description of the exception.
Description.
Example:
Note: Default exception handler internally uses the printStackTrace() method to print exception information to the console.
Try with multiple catch blocks
The way of handling an exception is varied from exception to exception hence for every exception raise a separate catch block is required .i.e try with multiple catch blocks is possible and recommended to use.
Example:
This approach is not recommended
because for any type of Exception
we are using the same catch block.{ . . . . } catch(Exception e) { default handler }
try
This approach is highly recommended
because for any exception raise
we are defining a separate catch block.{ . . . . catch(FileNotFoundException e) { use local file } catch(ArithmeticException e) { perform these Arithmetic operations } catch(SQLException e) { don't use oracle db, use mysql db } catch(Exception e) { default handler }
try
If try with multiple catch blocks presents then the order of catch blocks is very important it should be from child to parent by mistake if we are taking from parent to child then we will get Compile time error saying «exception xxx has already been caught».
{ public static void main(String[] args) { try { System.out.println(10/0); } catch(Exception e) { e.printStackTrace(); } catch(ArithmeticException e) { e.printStackTrace(); }}} Output: Compile time error. Test.java:13: exception java.lang.ArithmeticException has already been caught catch(ArithmeticException e)
class Test
{ public static void main(String[] args) { try { System.out.println(10/0); } catch(ArithmeticException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); }}} Output: Compile successfully.
class Test
Finally block
- It is never recommended to take clean up code inside try block because there is no guarantee for the execution of every statement inside a try.
It is never recommended to place clean up code inside the catch block because if there is no exception then catch block won’t be executed.
We require someplace to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether handled or not handled such type of place is nothing but finally block.
Hence the main objective of finally block is to maintain cleanup code.
Try { risky code } catch(x e) { handling code } finally { cleanup code }
Example:
The specialty of finally block is it will be executed always irrespective of whether the exception raised or not raised and whether handled or not handled.
Example 1: class Test { public static void main(String[] args) { try { System.out.println("try block executed"); } catch(ArithmeticException e) { System.out.println("catch block executed"); } finally { System.out.println("finally block executed"); }}} Output: Try block executed Finally block executed
Example 2: class Test { public static void main(String[] args) { try { System.out.println("try block executed"); System.out.println(10/0); } catch(ArithmeticException e) { System.out.println("catch block executed"); } finally { System.out.println("finally block executed"); }}} Output: Try block executed Catch block executed Finally block executed
class Test { public static void main(String[] args) { try { System.out.println("try block executed"); System.out.println(10/0); } catch(NullPointerException e) { System.out.println("catch block executed"); } finally { System.out.println("finally block executed"); }}} Output: Try block executed Finally block executed Exception in thread "main" java.lang.ArithmeticException: / by zero at Test.main(Test.java:8)
Example 3:
Return Vs Finally
Even though return present in try or catch blocks first finally will be executed and after that only return statement will be considered that is finally block dominates return statement.
class Test { public static void main(String[] args) { try { System.out.println("try block executed"); return; } catch(ArithmeticException e) { System.out.println("catch block executed"); } finally { System.out.println("finally block executed"); }}} Output: Try block executed Finally block executed
Example:
If the return statement presents try-catch and finally blocks then finally block return statement will be considered.
class Test { public static void main(String[] args) { System.out.println(methodOne()); } public static int methodOne(){ try { System.out.println(10/0); return 777; } catch(ArithmeticException e) { return 888; } finally{ return 999; }}} Output: 999
There is only one situation where the finally block won’t be executed is whenever we are using System.exit(0) method.
Then JVM itself will be shut down, in this case finally block won’t be executed.
i.e., System.exit(0); dominates finally block.Example: class Test { public static void main(String[] args) { try { System.out.println("try"); System.exit(0); } catch(ArithmeticException e) { System.out.println("catch block executed"); } finally { System.out.println("finally block executed"); }}} Output: Try
try
Note :
System.exit(0); instead of zero, we can take any integer value
zero means normal termination, non-zero means abnormal termination
this status code internally used by JVM, whether it is zero or non-zero there is no change in the result and effect is same
Difference between final, finally, and finalize
Final
- The Final is the modifier applicable for class, methods, and variables.
- If a class declared as the final then child class creation is not possible.
- If a method declared as the final then overriding of that method is not possible.
If a variable declared as the final then reassignment is not possible.
Finally
It is the block always associated with try-catch to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether handled or not handled.
FinalizeIt is a method which should be called by garbage collector always just before destroying an object to perform cleanup activities.
Note:
To maintain clean up code faunally block is recommended over the finalize() method because we can’t expect the exact behavior of GC.
Control flow in try-catch-finally
class Test { public static void main(String[] args){ try{ System.out.println("statement1"); System.out.println("statement2"); System.out.println("statement3"); } catch(Exception e){ System.out.println("statement4"); } finally { System.out.println("statement5"); } System.out.println("statement6"); } }
- Case 1: If there is no exception. 1, 2, 3, 5, 6 normal termination.
- Case 2: if an exception raised at statement 2 and corresponding catch block matched. 1,4,5,6 normal terminations.
- Case 3: if an exception raised at statement 2 and the corresponding catch block is not matched. 1,5 abnormal termination.
- Case 4: if an exception raised at statement 4 then it’s always abnormal termination but before the finally block will be executed.
- Case 5: if an exception raised at statement 5 or statement 6 its always abnormal termination.
Control flow in nested try-catch-finallyclass Test { public static void main(String[] args){ try{ System.out.println("statement1"); System.out.println("statement2"); System.out.println("statement3"); try{ System.out.println("statement4"); System.out.println("statement5"); System.out.println("statement6"); } catch(ArithmeticException e){ System.out.println("statement7"); } finally { System.out.println("statement8"); } System.out.println("statement9"); } catch(Exception e) { System.out.println("statement10"); } finally { System.out.println("statement11"); } System.out.println("statement12"); } }
- Case 1: if there is no exception. 1, 2, 3, 4, 5, 6, 8, 9, 11, 12 normal termination.
- Case 2: if an exception raised at statement 2 and corresponding catch block matched 1,10,11,12 normal terminations.
- Case 3: if an exception raised at statement 2 and the corresponding catch block is not matched 1, 11 abnormal termination.
- Case 4: if an exception raised at statement 5 and corresponding inner catch has matched 1, 2, 3, 4, 7, 8, 9, 11, 12 normal terminations.
- Case 5: if an exception raised at statement 5 and inner catch has not matched but the outer catch block has matched. 1, 2, 3, 4, 8, 10, 11, 12 normal termination.
- Case 6: if an exception raised at statement 5 and both inner and outer catch blocks are not matched. 1, 2, 3, 4, 8, 11 abnormal termination.
- Case 7: if an exception raised at statement 7 and the corresponding catch block matched 1, 2, 3, 4, 5, 6, 8, 10, 11, 12 normal terminations.
- Case 8: if an exception raised at statement 7 and the corresponding catch block not matched 1, 2, 3, 4, 5, 6, 8, 11 abnormal terminations.
- Case 9: if an exception raised at statement 8 and the corresponding catch block has matched 1, 2, 3, 4, 5, 6, 7, 10, 11,12 normal termination.
- Case 10: if an exception raised at statement 8 and the corresponding catch block not matched 1, 2, 3, 4, 5, 6, 7, 11 abnormal terminations.
- Case 11: if an exception raised at statement 9 and corresponding catch block matched 1, 2, 3, 4, 5, 6, 7, 8,10,11,12 normal termination.
- Case 12: if an exception raised at statement 9 and corresponding catch block not matched 1, 2, 3, 4, 5, 6, 7, 8, 11 abnormal terminations.
- Case 13: if an exception raised at statement 10 is always abnormal termination but before that finally block 11 will be executed.
- Case 14: if an exception raised at statement 11 or 12 is always abnormal termination.
Note: if we are not entering into the try block then the finally block won’t be executed. Once we entered into the try block without executing finally block we can’t come out.
We can take try-catch inside try i.e., nested try-catch is possible
The most specific exceptions can be handled by using inner try-catch and generalized exceptions can be handle by using outer try-catch.class Test { public static void main(String[] args){ try{ System.out.println(10/0); } catch(ArithmeticException e) { System.out.println(10/0); } finally{ String s=null; System.out.println(s.length()); }}} output : RE:NullPointerException
Note: Default exception handler can handle only one exception at a time and that is the most recently raised exception.
Various possible combinations of try-catch-finally1) Whenever we are writing try block compulsory we should write either catch or finally.
i.e., try without a catch or finally is invalid.2) Whenever we are writing catch block compulsory we should write a try.
i.e., catch without try is invalid.3) Whenever we are writing finally block compulsory we should write a try.
i.e., finally without try is invalid.4) In try-catch-finally order is important.
5) Within the try-catch-finally blocks, we can take try-catch-finally.
i.e., nesting of try-catch-finally is possible.
6) For try-catch-finally blocks curly braces are mandatory.public static void main(String[] args){ try {} catch(ArithmeticException e) {} }} Output: Compile and running successfully.
class Test1 {
public static void main(String[] args){ try {} catch(ArithmeticException e) {} catch(NullPointerException e) {} } } Output: Compile and running successfully.
class Test2 {
public static void main(String[] args){ try {} catch(ArithmeticException e) {} catch(ArithmeticException e) {} } } Output: Compile time error. Test1.java:7: exception java.lang.ArithmeticException has already been caught catch(ArithmeticException e)
class Test3 {
public static void main(String[] args){ try {} } } Output: Compile time error Test1.java:3: 'try' without 'catch' or 'finally' try
class Test4 {
public static void main(String[] args){ catch(Exception e) {} } } Output: Compile time error. Test1.java:3: 'catch' without 'try' catch(Exception e)
class Test5 {
public static void main(String[] args){ try {} System.out.println("hello"); catch(Exception e) {} } } Output: Compile time error. Test1.java:3: 'try' without 'catch' or 'finally' Try
class Test6 {
public static void main(String[] args){ try {} catch(Exception e) {} finally {} } } Output: Compile and running successfully.
class Test7 {
public static void main(String[] args){ try {} finally {} } } Output: Compile and running successfully.
class Test8 {
public static void main(String[] args){ try {} finally {} finally {} } } Output: Compile time error. Test1.java:7: 'finally' without 'try' Finally
class Test9 {
public static void main(String[] args){ try {} catch(Exception e) {} System.out.println("hello"); finally {} } } Output: Compile time error. Test1.java:8: 'finally' without 'try' Finally
class Test10 {
public static void main(String[] args){ try {} finally {} catch(Exception e) {} } } Output: Compile time error. Test1.java:7: 'catch' without 'try' catch(Exception e)
class Test11 {
public static void main(String[] args){ finally {} } } Output: Test1.java:3: 'finally' without 'try' Finally
class Test12 {
public static void main(String[] args){ try { try{} catch(Exception e){} } catch(Exception e) {} } } Output: Compile and running successfully.
class Test13 {
public static void main(String[] args){ try { } catch(Exception e) { try{} finally{} } } } Output: Compile and running successfully.
class Test14 {
public static void main(String[] args){ try { } catch(Exception e) { try{} catch(Exception e){} } finally{ finally{} } } } Output: Compile time error. Test1.java:11: 'finally' without 'try' finally{}
class Test15 {
public static void main(String[] args){ finally{} try{ } catch(Exception e){} } } Output: Compile time error. Test1.java:3: 'finally' without 'try' finally{}
class Test16 {
public static void main(String[] args){ try{ } catch(Exception e){} finally { try{} catch(Exception e){} finally{} } } } Output: Compile and running successfully.
class Test17 {
Throw statementSometimes we can create an Exception object explicitly and we can hand over to the JVM manually by using the throw keyword.
The result of the following 2 programs is exactly the same.
{ public static void main(String[] args){ System.out.println(10/0); }}
class Test
In this case creation of ArithmeticException object and handover to the JVM will be performed automatically by the main() method.
{ public static void main(String[] args){ System.out.println(10/0); }}
class Test
In this case, we are creating an exception objects explicitly and handover to the JVM manually.
Note: In general we can use throw keyword for customized exceptions but not for predefined exceptions.
Case 1:
throw e;
If e refers null then we will get NullPointerException.{ static ArithmeticException e=new ArithmeticException(); public static void main(String[] args){ throw e; } } Output: Runtime exception: Exception in thread "main" java.lang.ArithmeticException . . .
class Test1
{ static ArithmeticException e; public static void main(String[] args){ throw e; } } Output: Exception in thread "main" java.lang.NullPointerException at Test3.main(Test3.java:5)
class Test2
Case 2:
After throw statement we can’t take any statement directly otherwise we will get a compile-time error saying an unreachable statement.
Example:{ public static void main(String[] args){ System.out.println(10/0); System.out.println("hello"); } } Output: Runtime error: Exception in thread "main" java.lang.ArithmeticException: / by zero at Test3.main(Test3.java:4)
class Test1
Case 3:
We can use throw keyword only for Throwable types otherwise we will get a compile-time error saying incomputable types.
Example:{ public static void main(String[] args){ throw new Test3(); } }Output: Compile time error. Test3.java:4: incompatible types found : Test3 required: java.lang.Throwable throw new Test3();
class Test1
{ public static void main(String[] args){ throw new Test3(); } } Output: Runtime error: Exception in thread "main" Test3 at Test3.main(Test3.java:4)
class Test2 extends RuntimeException
Throws statement
In our program, if there is any chance of raising checked exception compulsory we should handle either by try-catch or by throws keyword otherwise the code won’t compile.
class Test3 { public static void main(String[] args){ PrinterWriter out=new PrintWriter("abc.txt"); out.println("hello"); } } CE : Unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown.
import java.io.*;
{ public static void main(String[] args){ Thread.sleep(5000); } } Unreported exception java.lang.InterruptedException; must be caught or declared to be thrown.
class Test3
We can handle this compile-time error by using the following 2 ways.
Example:
By using try-catch
{ public static void main(String[] args){ try { Thread.sleep(5000); } catch(InterruptedException e){} } } Output: Compile and running successfully
class Test3
By using throws keyword
We can use throws keyword to delicate the responsibility of exception handling to the caller method. Then the caller method is responsible to handle that exception.{ public static void main(String[] args)throws InterruptedException{ Thread.sleep(5000); } } Output: Compile and running successfully
class Test3
Note :
Hence the main objective of the «throws» keyword is to delicate the responsibility of exception handling to the caller method.
- «throws» keyword required only checked exceptions. Usage of throws for unchecked exceptions there is no use.
- «throws» keyword required only to convenes complier. The usage of throws keyword doesn’t prevent abnormal termination of the program.
- Hence recommended to use try-catch over throws keyword.
class Test { public static void main(String[] args)throws InterruptedException{ doStuff(); } public static void doStuff()throws InterruptedException{ doMoreStuff(); } public static void doMoreStuff()throws InterruptedException{ Thread.sleep(5000); } } Output: Compile and running successfully.
In the above program if we are removing at least one throws keyword then the program won’t compile.
Case 1:
we can use throws keyword only for Throwable types otherwise we will get a compile-time error saying incompatible types.
public static void main(String[] args) throws Test3 {} } Output: Compile time error Test3.java:2: incompatible types found : Test3 required: java.lang.Throwable public static void main(String[] args) throws Test3 . .
class Test3{
public static void main(String[] args) throws Test3 {} } Output: Compile and running successfully.
class Test3 extends RuntimeException{
Case 2: Example:
public static void main(String[] args){ throw new Exception(); } } Output: Compile time error. Test3.java:3: unreported exception java.lang.Exception; must be caught or declared to be thrown
class Test3{
public static void main(String[] args){ throw new Error(); } } Output: Runtime error Exception in thread "main" java.lang.Error at Test3.main(Test3.java:3)
class Test3{
Case 3:
In our program within the try block, if there is no chance of raising an exception then we can’t right catch block for that exception otherwise we will get a compile-time error saying exception XXX is never thrown in body of corresponding try statement. But this rule is applicable only for fully checked exceptions.
image7 image8
Case 4:
We can use throws keyword only for constructors and methods but not for classes.execp9:img
Exception handling keywords summary
1) try: To maintain risky code.
2) catch: To maintain handling code.
3) finally: To maintain cleanup code.
4) throw: To handover our created exception object to the JVM manually.
5) throws: To delegate the responsibility of exception handling to the caller method.
Various possible compile-time errors in exception handling
1) Exception XXX has already been caught.
2) Unreported exception XXX must be caught or declared to be thrown.
3) Exception XXX is never thrown in body of corresponding try statement.
4) Try without a catch or finally.
5) Catch without a try.
6) Finally without a try.
Incompatible types.
Found: test
Requried:java.lang.Throwable;
7) Unreachable statement.
Customized Exceptions (User-defined Exceptions)
Sometimes we can create our own exception to meet our programming requirements. Such types of exceptions are called customized exceptions (user-defined exceptions).
Example:
1) InSufficientFundsException
2) TooYoungException
3) TooOldExceptionclass TooYoungException extends RuntimeException { TooYoungException(String s) { super(s); } } class TooOldException extends RuntimeException { TooOldException(String s) { super(s); } } class CustomizedExceptionDemo { public static void main(String[] args){ int age=Integer.parseInt(args[0]); if(age>60) { throw new TooYoungException("please wait some more time.... u will get best match"); } else if(age<18 1="" age="" already="" by="" chance="" crossed....no="" details="" e-mail="" else="" get="" getting="" married="" match="" new="" of="" output:="" r="" scjp="" soon="" system.out.println="" throw="" toooldexception="" u="" will="" you="">java CustomizedExceptionDemo 61 Exception in thread "main" TooYoungException: please wait some more time.... u will get best match at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:21) 2)E:scjp>java CustomizedExceptionDemo 27 You will get match details soon by e-mail 3)E:scjp>java CustomizedExceptionDemo 9 Exception in thread "main" TooOldException: u r age already crossed....no chance of getting married at CustomizedExceptionDemo.main(CustomizedExceptionDemo.java:25)
Note: It is highly recommended to maintain our customized exceptions as unchecked by extending RuntimeException.
We can catch any Throwable type including Errors also.Example:
} catch(){ } //Valid
try {
Top-10 Exceptions
Exceptions are divided into two types.
They are:1) JVM Exceptions:
2) Programmatic exceptions:
JVM Exceptions
The exceptions are raised automatically by the JVM whenever a particular event occurs.
Example:
1) ArrayIndexOutOfBoundsException(AIOOBE)
2) NullPointerException (NPE).
Programmatic Exceptions
The exceptions which are raised explicitly by the programmer (or) by the API developer are called programmatic exceptions.
Example: 1) IllegalArgumentException(IAE).
Top 10 Exceptions
1) ArrayIndexOutOfBoundsException:
It is the child class of RuntimeException and hence it is unchecked. Raised automatically by the JVM whenever we are trying to access array element with out of range index. Example:
public static void main(String[] args){ int[] x=new int[10]; System.out.println(x[0]);//valid System.out.println(x[100]);//ArrayIndexOutOfBoundsException System.out.println(x[-100]);//ArrayIndexOutOfBoundsException } }
class Test{
2) NullPointerException: It is the child class of RuntimeException and hence it is unchecked. Raised automatically by the JVM, whenever we are trying to call any method on null.
class Test{ public static void main(String[] args){ String s=null; System.out.println(s.length()); //R.E: NullPointerException } }
3) StackOverFlowError :
It is the child class of Error and hence it is unchecked. Whenever we are trying to invoke the recursive method call JVM will raise StackOverFloeError automatically.
{ public static void methodOne() { methodTwo(); } public static void methodTwo() { methodOne(); } public static void main(String[] args) { methodOne(); } } Output: Run time error: StackOverFloeError
class Test
4) NoClassDefFound:
It is the child class of Error and hence it is unchecked. JVM will raise this error automatically whenever it is unable to find the required .class file. Example: java Test If Test.class is not available. Then we will get a NoClassDefFound error.
5) ClassCastException:
It is the child class of RuntimeException and hence it is unchecked. Raised automatically by the JVM whenever we are trying to typecast parent object to child type.
Example:
6) ExceptionInInitializerError:
It is the child class of Error and it is unchecked. Raised automatically by the JVM, if any exception occurs while performing static variable initialization and static block execution.
class Test{ static int i=10/0; } Output: Runtime exception: Exception in thread "main" java.lang.ExceptionInInitializerError . .
class Test{ static { String s=null; System.out.println(s.length()); }} Output: Runtime exception: Exception in thread "main" java.lang.ExceptionInInitializerError
7) IllegalArgumentException:
It is the child class of RuntimeException and hence it is unchecked. Raised explicitly by the programmer (or) by the API developer to indicate that a method has been invoked with inappropriate argument.
class Test{ public static void main(String[] args){ Thread t=new Thread(); t.setPriority(10);//valid t.setPriority(100);//invalid }} Output: Runtime exception Exception in thread "main" java.lang.IllegalArgumentException.
NumberFormatException:
It is the child class of IllegalArgumentException and hence is unchecked. Raised explicitly by the programmer or by the API developer to indicate that we are attempting to convert string to the number. But the string is not properly formatted.
class Test{ public static void main(String[] args){ int i=Integer.parseInt("10"); int j=Integer.parseInt("ten"); }} Output: Runtime Exception Exception in thread "main" java.lang.NumberFormatException: For input string: "ten"
9) IllegalStateException:
It is the child class of RuntimeException and hence it is unchecked. Raised explicitly by the programmer or by the API developer to indicate that a method has been invoked at an inappropriate time.Example:
Once the session expires we can’t call any method on the session object otherwise we will get IllegalStateException
System.out.println(session.getId()); session.invalidate(); System.out.println(session.getId()); // IllgalstateException
HttpSession session=req.getSession();
10) AssertionError:
It is the child class of Error and hence it is unchecked. Raised explicitly by the programmer or by API developer to indicate that the Assert statement fails.Example:
assert(false);
Exception/Error Raised automatically by JVM(JVM Exceptions)
1) AIOOBE
2) NPE(NullPointerException)
3) StackOverFlowError
4) NoClassDefFoundError
5) CCE(ClassCastException)
6) ExceptionInInitializerErrorException/Error Raised explicitly either by the programmer or by API developer (Programmatic Exceptions).
1) IAE(IllegalArgumentException)
2) NumberFormatException
3) IllegalStateException
4) AssertionError
1.7 Version Enhancements
As part of 1.7 version enhancements in Exception Handling the following 2 concepts introduced
try with resources
multi-catch block
try with resources
Until 1.5 version it is highly recommended to write finally block to close all resources which are open as part of the try block.try{ br=new BufferedReader(new FileReader("abc.txt")); //use br based on our requirements } catch(IOException e) { // handling code } finally { if(br != null) br.close(); }
BufferedReader br=null;
problems in this approach
1) Compulsory programmer is required to close all opened resources which increases the complexity of the programming
2) Compulsory we should write finally block explicitly which increases the length of the code and reviews readability.
To overcome these problems Sun People introduced «try with resources» in 1.7 versions.
The main advantage of «try with resources» is
the resources which are opened as part of try block will be closed automatically
Once the control reaches the end of the try block either normally or abnormally and hence we are not required to close explicitlydue to the complexity of programming will be reduced, it is not required to write finally block explicitly and hence the length of the code will be reduced and readability will be improved.
{ use be based on our requirement, br will be closed automatically , Onec control reaches end of try either normally or abnormally and we are not required to close explicitly } catch(IOException e) { // handling code }
try(BufferedReader br=new BufferedReader(new FileReader("abc.txt")))
We can declare any no of resources but all these resources should be separated with ;(semicolon)
{ ------------- ------------- }
try(R1 ; R2 ; R3)
All resources should be auto closable resources, a resource is said to be auto closable if and only if the corresponding class implements the java.lang.AutoClosable interface either directly or indirectly.
All resource reference variables are implicitly final and hence we can’t perform reassignment within the try block.
{ br=new BufferedReader(new FileReader("abc.txt")); } output : CE : Can't reassign a value to final variable br . .
try(BufferedReader br=new BufferedReader(new FileReader("abc.txt"))) ;
Until 1.6 version try should be followed by either catch or finally but 1.7 version we can take only try with the resource without a catch or finally
{ //valid } . .
try(R)
The main advantage of «try with resources» finally block will become dummy because we are not required to close resources explicitly.
Multi catch block
Even though Multiple Exceptions having same handling code we have to write a separate catch block for every exception, it increases the length of the code and reviews readability
----------------- ----------------- } catch(ArithmeticException e) { e.printStackTrace(); } catch(NullPointerException e) { e.printStackTrace(); } catch(ClassCastException e) { System.out.println(e.getMessage()); } catch(IOException e) { System.out.println(e.getMessage()); }
try{
To overcome this problem Sun People introduced the «Multi catch block» concept in 1.7 version.
The main advantage of the multi-catch block is we can write a single catch block, which can handle multiple different exceptions
----------------- ----------------- } catch(ArithmeticException | NullPointerException e) { e.printStackTrace(); } catch(ClassCastException | IOException e) { System.out.println(e.getMessage()); }
try{
In multi-catch block, there should not be any relation between Exception types(either child to parent Or parent to child Or same type, otherwise we will get Compile time error )
Example:
----------------- ----------------- } catch(ArithmeticException | Exception e) { // compile time error e.printStackTrace();//invalid }
try{
Exception Propagation
Within a method if an exception raised and if that method doesn’t handle that exception then the Exception object will be propagated to the caller then the caller method is responsible to handle those exceptions. This process is called Exception Propagation.
Rethrowing an Exception
To convert the one exception type to another exception type, we can use the rethrowing exception concept.
{ public static void main(String[] args){ try { System.out.println(10/0); } catch(ArithmeticException e) { throw new NullPointerException(); } } } output: RE:NPE
class Test