Содержание
- Встроенные исключения в Java с примерами
- Resolve Unreported Exception IOException Must Be Caught or Declared to Be Thrown in Java
- Demonstration of Unreported IOException
- Use try-catch to Catch Unreported IOException
- Use the throws Keyword to Eradicate IOException
Встроенные исключения в 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, и помогите другим вундеркиндам.
Пожалуйста, пишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по обсуждаемой выше теме.
Источник
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.
Источник
Improve Article
Save Article
Improve Article
Save Article
Types of Exceptions in Java
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:
- Arithmetic exception : It is thrown when an exceptional condition has occurred in an arithmetic operation.
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"
);
}
}
}
Output:
Can't divide a number by 0
- 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.
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"
);
}
}
}
Output:
Array Index is Out Of Bounds
- ClassNotFoundException : This Exception is raised when we try to access a class whose definition is not found.
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());
}
}
Output:
ClassNotFoundException
- FileNotFoundException : This Exception is raised when a file is not accessible or does not open.
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"
);
}
}
}
Output:
File does not exist
- IOException : It is thrown when an input-output operation failed or interrupted
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();
}
}
Output:
error: unreported exception IOException; must be caught or declared to be thrown
- InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
class
Geeks {
public
static
void
main(String args[])
{
Thread t =
new
Thread();
t.sleep(
10000
);
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared to be thrown
- NoSuchMethodException : t is thrown when accessing a method which is not found.
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();
}
}
Output:
error: exception NoSuchMethodException is never thrown in body of corresponding try statement
- NullPointerException : This exception is raised when referring to the members of a null object. Null represents nothing
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.."
);
}
}
}
Output:
NullPointerException..
- NumberFormatException : This exception is raised when a method could not convert a string into a numeric format.
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"
);
}
}
}
Output:
Number format exception
- StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is either negative than the size of the 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"
);
}
}
}
Output:
StringIndexOutOfBoundsException
Some other important Exceptions
- 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;
}
}
Output:
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();
}
}
Output:
Exception in thread "main" java.lang.StackOverflowError
- NoClassDefFoundError
class
Test
{
public
static
void
main(String[] args)
{
System.out.println(
"HELLO GEEKS"
);
}
}
Output:
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
Code 1:class
Test {
static
int
x =
10
/
0
;
public
static
void
main(String[] args)
{
}
}
Output:
Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.ArithmeticException: / by zero
Code 2 :
class
Test {
static
{
String s =
null
;
System.out.println(s.length());
}
public
static
void
main(String[] args)
{
}
}
Output:
Exception in thread "main" java.lang.ExceptionInInitializerError Caused by: java.lang.NullPointerException
Explanation : The above exception occurs whenever while executing static variable assignment and static block if any Exception occurs.
- IllegalArgumentException
class
Test {
public
static
void
main(String[] args)
{
Thread t =
new
Thread();
Thread t1 =
new
Thread();
t.setPriority(
7
);
t1.setPriority(
17
);
}
}
Output:
Exception in thread "main" java.lang.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
class
Test {
public
static
void
main(String[] args)
{
Thread t =
new
Thread();
t.start();
t.start();
}
}
Output:
Exception in thread "main" java.lang.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
class
Test {
public
static
void
main(String[] args)
{
assert
(x >=
10
);
}
}
Output:
Exception in thread "main" java.lang.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.
Это программа, которую я пытаюсь скомпилировать с помощью jdk. «Satya» в программе относится к базе данных базы данных msaccess. Когда я пытаюсь скомпилировать, она показывает ошибку, например "MyClass.java:0:error:unreported exception ClassNotFoundException;must be caught or declared to be thrown"
Даже если я изменю исключение в программе из SQLException
в Exception, оно компилируется успешно. Но бросая исключение при запуске программы. Как выполнить?
import java.sql.*;
class MyClass
{
public static void main(String args[])
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:satya","","");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from studentinfo");
while(rs.next())
{
System.out.println(rs.getInt(1)+"t"+
rs.getString(2)+"t"+
rs.getString(3)+"t");
}
rs.close();
st.close();
}
catch (SQLException e) {
System.out.println("<P>" + "There was an error doing the query:");
System.out.println ("<PRE>" + e + "</PRE> n <P>");
}
}
}
23 фев. 2015, в 13:41
Поделиться
Источник
2 ответа
ClassNotFoundException
— это подкласс Exception, поэтому вы передаете компилятор. Класс SQLException
не ClassNotFoundException
. Так как forName()
Class
объявлен как » throws ClassNotFoundException
«, компилятор потребует, чтобы вы завернули вызов метода с помощью блока try/catch или предложения throws
метода caller. Блок catch
должен использовать либо ClassNotFoundException
либо один из его родительских классов Exception
.
Вам нужно выяснить, какое исключение выбрасывает во время выполнения, чтобы проверить, почему он не работает.
Aram Paronikyan
23 фев. 2015, в 10:21
Поделиться
один из ваших методов бросает ClassNotFoundException
и вы несете ответственность за эти исключения. Быстрое исправление
public static void main(String args[]) throws Exception
в этом случае исключение печатается на вашей консоли (пожалуйста, разверните свой вопрос с этим выходом).
Кроме того, убедитесь, что вы добавили библиотеку драйверов jdbc в свой проект.
Stefan Beike
23 фев. 2015, в 09:34
Поделиться
Ещё вопросы
- 1Что занимает время на IIS, если это не мой код? Запрос в очереди?
- 0Сначала добавьте текст в jQuery после завершения процесса
- 0Изменение размера divs ширина и высота в браузере изменить размер с помощью CSS
- 0Неизвестная ошибка с шаблонами
- 1Не удается отформатировать мою дату в нужном формате?
- 0динамические селекторы добавляются при выполнении функции
- 0Параметры метода
- 0Удалить несколько выбранных строк DataTable одним щелчком мыши?
- 1Что означает объект, который должен быть инициирован один раз, но вызван разными потоками? (Я имею в виду сервлеты ..)
- 0Как значения Null программно реализуются в базе данных mysql? [Дубликат]
- 0Большое приложение чата Mysql db для хранения сообщений 1 строка на сообщение или добавление всей цепочки к 1 длинному текстовому файлу
- 0Редактировать текстовый файл в C ++
- 0Y-ось углового NVD3 устанавливает минимальное значение данных в качестве максимального значения диапазона
- 0строительный массив внутри 2 петли
- 0Как создать таблицу в базе данных MySQL через приложение Android?
- 0Handsontable не открывается в диалоге jQuery UI?
- 1Невозможно получить данные из дочерней формы в выбранную родительскую ячейку DataGridView.
- 0Изображения не отображаются в строке
- 1Android-SDCard
- 0блокировка матрицы дает ошибку сегментации
- 0MySQL положить в дубликаты идентификаторов
- 0Проблема с компиляцией функции, которая возвращает строку &
- 0Подход для проверки всех текстовых полей с использованием Jquery validate
- 0извлечь список функций в заголовочном файле
- 0Как изменить данные в связанном списке c ++ 3
- 0PHP XML xlink: атрибуты href [дубликаты]
- 0JQuery не селектор не работает на активный класс
- 0Как вызвать функцию в контроллере AngularJS с помощью метода $ scope?
- 1Переключить класс элемента с VueJs2 внутри v-for, это правильный путь?
- 1добавление записей в xsd файл с использованием linq и C #
- 1AsyncTask не отображается на PreExecute
- 0Проверка Jquery на содержание div
- 0динамический объект массива json
- 0QGraphicsScene отключить установку правого и нижнего поля
- 1C # программа зависает на Socket.Accept ()
- 1Событие listbox onmouseover для изменения текста текстового блока
- 0Не удается решить проблему спрайтов CSS
- 1Кэширование ответа на POST-запрос к функции Firebase
- 0поместите div поверх видео <object> в HTML CSS
- 0Вызов контроллера при выборе меню в одностраничном приложении — MVC & angularJs
- 1Java слушатель для щелчка мышью по любому текстовому полю на экране
- 0MySQL Как динамически выбирать, из какой таблицы получать данные при создании представления
- 0Чтение данных из файла — сохранение в переменных или чтение снова и снова
- 1Python регулярное выражение с разделителями-запятыми значение CSV из 3 символов
- 0Подходим строки с акцентами
- 0Использование Bootstrap & проверки формы — получение изображения галочки справа от поля ввода
- 0Почему все привязки разрешаются каждый цикл $ digest?
- 0как создать директиву для daterangepicker?
- 0Ошибка типа: не удается прочитать свойство ‘0’ неопределенного AngularJS
- 0codeigniter: данные не вставляются в таблицу с использованием insert_batch
Recommended Answers
there are two lines where you call that method; you caught the exception for the second one, but not the first
Jump to Post
there are two lines of
Class.forName ("oracle.jdbc.driver.OracleDriver");
in your code
Jump to Post
All 6 Replies
bugmenot
25
Posting Whiz in Training
15 Years Ago
there are two lines where you call that method; you caught the exception for the second one, but not the first
15 Years Ago
I’m not clear as to what is the first method. I thought that I had a Try-Catch block for each method. Can you tell me how to modify my code to make it compile.
Thank you.
bugmenot
25
Posting Whiz in Training
15 Years Ago
there are two lines of
Class.forName ("oracle.jdbc.driver.OracleDriver");
in your code
15 Years Ago
Thank you for the suggestion.
I commented out Line 8 and that eliminated the two compiling errors.
However, I now have another compiling error:
C:Documents and SettingsJ. SeaderDesktopJava ApplicationsNewProfileTest.java:24: unreported exception java.sql.SQLException; must be caught or declared to be thrown
(«jdbc:oracle:thin:@10.52.38.91:1521:PROFILE»,»newprofi1e»,»newprofile»);
^
1 error
Tool completed with exit code 1
What else do I need to do?
Thank you
peter_budo
2,532
Code tags enforcer
Team Colleague
Featured Poster
15 Years Ago
You can do it like this
import java.sql.*;
import java.math.*;
public class NewProfileTest
{
public static void main(String[] args)
{
Connection con = null;
Statement stmt;
try
{
Class.forName ("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection
("jdbc:oracle:thin:@10.25.83.19:1512:PROFILE","newprofile","newprofile");
stmt = con.createStatement();
stmt.close();
con. close();
}
catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
catch(SQLException ex)
{
System.err.println("sQLException: " + ex.getMessage());
}
}
}
or leave it as you have it and remove line 8 Class.forName ("oracle.jdbc.driver.OracleDriver");
plus line 10 onli declaration Connection con =null;
15 Years Ago
Thank you.
The revised code compiles successfully.
I will now try queries to the database.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
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
- Java Error
unreported exception must be caught or declared to be thrown
- Handle Exception in the Calling Function in Java
- Make the Calling Function Throw the Same Exception in Java
Java is an object-oriented, strongly typed and compiled language and has the concept of classes to leverage different aspects of programming like inheritance and polymorphism. It is also good support for handling exceptions due to highly nested functions.
This article will demonstrate the unreported exception must be caught or declared to be thrown
compile time error in Java.
Java Error unreported exception must be caught or declared to be thrown
Consider the following code sample.
public class MyApp
{
public static void main(String[] args) {
System.out.println("Hello World");
System.out.println(divide(3,0));
}
public static int divide(int a, int b) throws Exception {
int c = a / b;
return c;
}
}
The following error is obtained when the above code sample is compiled using javac MyApp.java
.
MyApp.java:7: error: unreported exception Exception; must be caught or declared to be thrown
System.out.println(divide(3,0));
^
1 error
So what is happening here?
The function divide(int a, int b)
throws an Exception
which is not caught or handled anywhere in the calling function, which in this case is main(String[] args)
. It can be resolved by handling the exception or making the calling function throw the same exception.
Handle Exception in the Calling Function in Java
So in the last section, this was one of the approaches to resolve the error. Let’s understand it with an example considering the code sample discussed above.
public class MyApp
{
public static void main(String[] args) {
System.out.println("Hello World");
try {
System.out.println(divide(3,0));
} catch(Exception e) {
System.out.println("Division by zero !!!");
}
}
public static int divide(int a, int b) throws Exception {
int c = a / b;
return c;
}
}
Now when we try to compile the code, it gets compiled successfully, and the following output is obtained on running the code.
Hello World
Division by zero !!!
Thus, the exception is now handled in the main
method, and the print
statement in the catch
block is executed.
Make the Calling Function Throw the Same Exception in Java
So the other approach is to make the calling function also throw the same exception. Let’s take an example of how that can be achieved.
public class MyApp
{
public static void main(String[] args) throws Exception {
System.out.println("Hello World");
try {
performOperation();
} catch (Exception e) {
System.out.println("Division by zero!!");
}
}
public static void performOperation() throws Exception {
divide(3, 0);
}
public static int divide(int a, int b) throws Exception {
int c = a / b;
return c;
}
}
So we have taken the previous example and added an extra function, performOperation()
, in between. We have made the performOperation()
function also throw the same Exception
as divide(int a, int b)
; thus, it gets compiled successfully, and the same output can be obtained.