Меню

Ошибка во время исполнения java

Error is an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing. 

The most common errors can be broadly classified as follows:

1. Run Time Error: 

Run Time errors occur or we can say, are detected during the execution of the program. Sometimes these are discovered when the user enters an invalid data or data which is not relevant. Runtime errors occur when a program does not contain any syntax errors but asks the computer to do something that the computer is unable to reliably do. During compilation, the compiler has no technique to detect these kinds of errors. It is the JVM (Java Virtual Machine) that detects it while the program is running. To handle the error during the run time we can put our error code inside the try block and catch the error inside the catch block. 

For example: if the user inputs a data of string format when the computer is expecting an integer, there will be a runtime error. Example 1: Runtime Error caused by dividing by zero 

Java

class DivByZero {

    public static void main(String args[])

    {

        int var1 = 15;

        int var2 = 5;

        int var3 = 0;

        int ans1 = var1 / var2;

        int ans2 = var1 / var3;

        System.out.println(

            "Division of va1"

            + " by var2 is: "

            + ans1);

        System.out.println(

            "Division of va1"

            + " by var3 is: "

            + ans2);

    }

}

Runtime Error in java code:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at DivByZero.main(File.java:14)

Example 2: Runtime Error caused by Assigning/Retrieving Value from an array using an index which is greater than the size of the array 

Java

class RTErrorDemo {

    public static void main(String args[])

    {

        int arr[] = new int[5];

        arr[9] = 250;

        System.out.println("Value assigned! ");

    }

}

RunTime Error in java code:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at RTErrorDemo.main(File.java:10)

2. Compile Time Error: 

Compile Time Errors are those errors which prevent the code from running because of an incorrect syntax such as a missing semicolon at the end of a statement or a missing bracket, class not found, etc. These errors are detected by the java compiler and an error message is displayed on the screen while compiling. Compile Time Errors are sometimes also referred to as Syntax errors. These kind of errors are easy to spot and rectify because the java compiler finds them for you. The compiler will tell you which piece of code in the program got in trouble and its best guess as to what you did wrong. Usually, the compiler indicates the exact line where the error is, or sometimes the line just before it, however, if the problem is with incorrectly nested braces, the actual error may be at the beginning of the block. In effect, syntax errors represent grammatical errors in the use of the programming language. 

Example 1: Misspelled variable name or method names 

Java

class MisspelledVar {

    public static void main(String args[])

    {

        int a = 40, b = 60;

        int Sum = a + b;

        System.out.println(

            "Sum of variables is "

            + sum);

    }

}

Compilation Error in java code:

prog.java:14: error: cannot find symbol
            + sum);
              ^
  symbol:   variable sum
  location: class MisspelledVar
1 error

Example 2: Missing semicolons 

Java

class PrintingSentence {

    public static void main(String args[])

    {

        String s = "GeeksforGeeks";

        System.out.println("Welcome to " + s)

    }

}

Compilation Error in java code:

prog.java:8: error: ';' expected
        System.out.println("Welcome to " + s)
                                             ^
1 error

Example: Missing parenthesis, square brackets, or curly braces 

Java

class MissingParenthesis {

    public static void main(String args[])

    {

        System.out.println("Printing 1 to 5 n");

        int i;

        for (i = 1; i <= 5; i++ {

            System.out.println(i + "n");

        }

    }

}

Compilation Error in java code:

prog.java:10: error: ')' expected
        for (i = 1; i <= 5; i++ {
                               ^
1 error

Example: Incorrect format of selection statements or loops 

Java

class IncorrectLoop {

    public static void main(String args[])

    {

        System.out.println("Multiplication Table of 7");

        int a = 7, ans;

        int i;

        for (i = 1, i <= 10; i++) {

            ans = a * i;

            System.out.println(ans + "n");

        }

    }

}

Compilation Error in java code:

prog.java:12: error: not a statement
        for (i = 1, i <= 10; i++) {
                      ^
prog.java:12: error: ';' expected
        for (i = 1, i <= 10; i++) {
                                ^
2 errors

Logical Error: A logic error is when your program compiles and executes, but does the wrong thing or returns an incorrect result or no output when it should be returning an output. These errors are detected neither by the compiler nor by JVM. The Java system has no idea what your program is supposed to do, so it provides no additional information to help you find the error. Logical errors are also called Semantic Errors. These errors are caused due to an incorrect idea or concept used by a programmer while coding. Syntax errors are grammatical errors whereas, logical errors are errors arising out of an incorrect meaning. For example, if a programmer accidentally adds two variables when he or she meant to divide them, the program will give no error and will execute successfully but with an incorrect result. 

Example: Accidentally using an incorrect operator on the variables to perform an operation (Using ‘/’ operator to get the modulus instead using ‘%’) 

Java

public class LErrorDemo {

    public static void main(String[] args)

    {

        int num = 789;

        int reversednum = 0;

        int remainder;

        while (num != 0) {

            remainder = num / 10;

            reversednum

                = reversednum * 10

                  + remainder;

            num /= 10;

        }

        System.out.println("Reversed number is "

                           + reversednum);

    }

}

Output:

Reversed number is 7870

Example: Displaying the wrong message 

Java

class IncorrectMessage {

    public static void main(String args[])

    {

        int a = 2, b = 8, c = 6;

        System.out.println(

            "Finding the largest number n");

        if (a > b && a > c)

            System.out.println(

                a + " is the largest Number");

        else if (b > a && b > c)

            System.out.println(

                b + " is the smallest Number");

        else

            System.out.println(

                c + " is the largest Number");

    }

}

Output:

Finding the largest number 

8 is the smallest Number

Syntax Error:

Syntax and Logical errors are faced by Programmers.

Spelling or grammatical mistakes are syntax errors, for example, using an uninitialized variable, using an undefined variable, etc., missing a semicolon, etc.

int x, y;
x = 10 // missing semicolon (;)
z = x + y; // z is undefined, y in uninitialized.

Syntax errors can be removed with the help of the compiler.

Error is an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing. 

The most common errors can be broadly classified as follows:

1. Run Time Error: 

Run Time errors occur or we can say, are detected during the execution of the program. Sometimes these are discovered when the user enters an invalid data or data which is not relevant. Runtime errors occur when a program does not contain any syntax errors but asks the computer to do something that the computer is unable to reliably do. During compilation, the compiler has no technique to detect these kinds of errors. It is the JVM (Java Virtual Machine) that detects it while the program is running. To handle the error during the run time we can put our error code inside the try block and catch the error inside the catch block. 

For example: if the user inputs a data of string format when the computer is expecting an integer, there will be a runtime error. Example 1: Runtime Error caused by dividing by zero 

Java

class DivByZero {

    public static void main(String args[])

    {

        int var1 = 15;

        int var2 = 5;

        int var3 = 0;

        int ans1 = var1 / var2;

        int ans2 = var1 / var3;

        System.out.println(

            "Division of va1"

            + " by var2 is: "

            + ans1);

        System.out.println(

            "Division of va1"

            + " by var3 is: "

            + ans2);

    }

}

Runtime Error in java code:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at DivByZero.main(File.java:14)

Example 2: Runtime Error caused by Assigning/Retrieving Value from an array using an index which is greater than the size of the array 

Java

class RTErrorDemo {

    public static void main(String args[])

    {

        int arr[] = new int[5];

        arr[9] = 250;

        System.out.println("Value assigned! ");

    }

}

RunTime Error in java code:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at RTErrorDemo.main(File.java:10)

2. Compile Time Error: 

Compile Time Errors are those errors which prevent the code from running because of an incorrect syntax such as a missing semicolon at the end of a statement or a missing bracket, class not found, etc. These errors are detected by the java compiler and an error message is displayed on the screen while compiling. Compile Time Errors are sometimes also referred to as Syntax errors. These kind of errors are easy to spot and rectify because the java compiler finds them for you. The compiler will tell you which piece of code in the program got in trouble and its best guess as to what you did wrong. Usually, the compiler indicates the exact line where the error is, or sometimes the line just before it, however, if the problem is with incorrectly nested braces, the actual error may be at the beginning of the block. In effect, syntax errors represent grammatical errors in the use of the programming language. 

Example 1: Misspelled variable name or method names 

Java

class MisspelledVar {

    public static void main(String args[])

    {

        int a = 40, b = 60;

        int Sum = a + b;

        System.out.println(

            "Sum of variables is "

            + sum);

    }

}

Compilation Error in java code:

prog.java:14: error: cannot find symbol
            + sum);
              ^
  symbol:   variable sum
  location: class MisspelledVar
1 error

Example 2: Missing semicolons 

Java

class PrintingSentence {

    public static void main(String args[])

    {

        String s = "GeeksforGeeks";

        System.out.println("Welcome to " + s)

    }

}

Compilation Error in java code:

prog.java:8: error: ';' expected
        System.out.println("Welcome to " + s)
                                             ^
1 error

Example: Missing parenthesis, square brackets, or curly braces 

Java

class MissingParenthesis {

    public static void main(String args[])

    {

        System.out.println("Printing 1 to 5 n");

        int i;

        for (i = 1; i <= 5; i++ {

            System.out.println(i + "n");

        }

    }

}

Compilation Error in java code:

prog.java:10: error: ')' expected
        for (i = 1; i <= 5; i++ {
                               ^
1 error

Example: Incorrect format of selection statements or loops 

Java

class IncorrectLoop {

    public static void main(String args[])

    {

        System.out.println("Multiplication Table of 7");

        int a = 7, ans;

        int i;

        for (i = 1, i <= 10; i++) {

            ans = a * i;

            System.out.println(ans + "n");

        }

    }

}

Compilation Error in java code:

prog.java:12: error: not a statement
        for (i = 1, i <= 10; i++) {
                      ^
prog.java:12: error: ';' expected
        for (i = 1, i <= 10; i++) {
                                ^
2 errors

Logical Error: A logic error is when your program compiles and executes, but does the wrong thing or returns an incorrect result or no output when it should be returning an output. These errors are detected neither by the compiler nor by JVM. The Java system has no idea what your program is supposed to do, so it provides no additional information to help you find the error. Logical errors are also called Semantic Errors. These errors are caused due to an incorrect idea or concept used by a programmer while coding. Syntax errors are grammatical errors whereas, logical errors are errors arising out of an incorrect meaning. For example, if a programmer accidentally adds two variables when he or she meant to divide them, the program will give no error and will execute successfully but with an incorrect result. 

Example: Accidentally using an incorrect operator on the variables to perform an operation (Using ‘/’ operator to get the modulus instead using ‘%’) 

Java

public class LErrorDemo {

    public static void main(String[] args)

    {

        int num = 789;

        int reversednum = 0;

        int remainder;

        while (num != 0) {

            remainder = num / 10;

            reversednum

                = reversednum * 10

                  + remainder;

            num /= 10;

        }

        System.out.println("Reversed number is "

                           + reversednum);

    }

}

Output:

Reversed number is 7870

Example: Displaying the wrong message 

Java

class IncorrectMessage {

    public static void main(String args[])

    {

        int a = 2, b = 8, c = 6;

        System.out.println(

            "Finding the largest number n");

        if (a > b && a > c)

            System.out.println(

                a + " is the largest Number");

        else if (b > a && b > c)

            System.out.println(

                b + " is the smallest Number");

        else

            System.out.println(

                c + " is the largest Number");

    }

}

Output:

Finding the largest number 

8 is the smallest Number

Syntax Error:

Syntax and Logical errors are faced by Programmers.

Spelling or grammatical mistakes are syntax errors, for example, using an uninitialized variable, using an undefined variable, etc., missing a semicolon, etc.

int x, y;
x = 10 // missing semicolon (;)
z = x + y; // z is undefined, y in uninitialized.

Syntax errors can be removed with the help of the compiler.

Чтобы разобраться, в чем разница между ошибками времени компиляции и ошибками времени выполнения в Java, разберемся в сути каждого вида.

Ошибки времени компиляции

Это синтаксические ошибки в коде, которые препятствуют его компиляции.

Пример

public class Test{
   public static void main(String args[]){
      System.out.println("Hello")
   }
}

Итог

C:Sample>Javac Test.java
Test.java:3: error: ';' expected
   System.out.println("Hello")

Ошибки времени выполнения

Исключение (или исключительное событие) – это проблема, возникающая во время выполнения программы. Когда возникает исключение, нормальный поток программы прерывается, и программа / приложение прерывается ненормально, что не рекомендуется, поэтому эти исключения должны быть обработаны.

Пример

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

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

Итог

C:>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
   FileReader fr = new FileReader(file);
                   ^
1 error

На чтение 2 мин. Просмотров 5 Опубликовано 25.05.2021

Рассмотрим следующий сегмент кода Java, хранящийся в файле с именем JollyMessage.java:

 
//На экран выводится веселое сообщение! 
class Jollymessage
{

public static void main (String [] args) {

//Записываем сообщение в окно терминала
System.out.println ("Ho Ho Ho!");

}
}

При выполнении программы этот код выдаст сообщение об ошибке выполнения. Другими словами, где-то была допущена ошибка, но ошибка не будет идентифицирована, когда программа скомпилирована , только когда она запущена .

Отладка

В приведенном выше примере обратите внимание, что класс называется «Jollymessage», а имя файла – JollyMessage.java .

Java чувствительна к регистру. Компилятор не будет жаловаться, потому что технически с кодом все в порядке. Он создаст файл класса, который точно соответствует имени класса (например, Jollymessage.class). Когда вы запустите программу под названием JollyMessage, вы получите сообщение об ошибке, потому что нет файла с именем JollyMessage.class.

Ошибка, которую вы получаете при запуске программа с неправильным именем:

 
 Исключение в потоке «main» java.lang.NoClassDefFoundError: JollyMessage (неверно  name: JollyMessage) .. 

Общие решения для ошибок во время выполнения

Если ваша программа успешно компилируется, но не выполняется, проверьте код для типичных ошибок:

  • Несоответствующие одинарные и двойные кавычки
  • Отсутствующие кавычки для строк
  • Неправильные операторы сравнения (например, отсутствие двойных знаков равенства для обозначения присваивания)
  • Ссылка на несуществующие или несуществующие объекты с использованием заглавных букв, указанных в коде
  • Ссылка на объект, не имеющий свойств

Работа в интегрированных средах разработки, таких как Eclipse, может помочь вам избежать Ошибки в стиле «опечатка».

Для отладки промышленных программ Java запустите отладчик веб-браузера – вы должны увидеть сообщение об ошибке в шестнадцатеричном формате, которое может помочь изолировать конкретная причина проблемы.

В некоторых ситуациях проблема может заключаться не в вашем коде, а в вашей виртуальной машине Java. Если JVM задыхается, она может выдать ошибку времени выполнения, несмотря на отсутствие недостатков в кодовой базе программы. Сообщение отладчика браузера поможет изолировать ошибки, вызванные кодом, от ошибок, вызванных JVM..

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка во время загрузки эксель
  • Ошибка винрар диагностические сообщения