Meta tags:
description= Aprende las excepciones PHP: cómo lanzar y capturar errores con try/catch/finally, métodos de la clase Exception, multi-catch y clases de excepción…;
Headings (most frequently used words):
una, excepción, capturar, de, excepciones, php, exception, qué, es, lanzar, con, try, catch, finally, leer, información, múltiples, tipos, crear, personalizadas, buenas, prácticas, cómo, fluye, el, control, práctica,
Text of the page (most frequently used words):
php (112), una (23), excepción (22), que (21), try (20), excepciones (20), catch (19), para (15), aprender (15), mysql (15), #finally (14), exception (14), echo (12), con (10), las (10), balance (10), capturar (9), bloque (9), como (9), copiar (9), los (8), code (8), tipos (8), this (8), html (7), cómo (7), errores (7), manejo (7), más (7), function (7), string (7), error (7), datos (7), new (7), ajax (7), getmessage (6), throwable (6), throw (6), xml (6), w3docs (5), json (5), crear (5), personalizadas (5), qué (5), archivos (5), lugar (5), donde (5), __construct (5), errors (5), array (5), public (5), métodos (5), account (5), clases (5), age (5), cannot (5), withdraw (5), base (5), arrays (5), formatter (5), color (5), generator (4), práctica (4), control (4), lanzar (4), next (4), tanto (4), puede (4), clase (4), flujo (4), por (4), getcode (4), captura (4), typeerror (4), código (4), return (4), class (4), insufficientfundsexception (4), not (4), salida (4), input (4), amount (4), divide (4), data (4), bucle (4), encoder (3), editor (3), cuestionarios (3), ejercicios (3), javascript (3), css (3), usa (3), manejar (3), block (3), normal (3), registra (3), manejador (3), error_log (3), legible (3), lanza (3), puedas (3), constructor (3), anterior (3), private (3), extends (3), cuando (3), tus (3), rangeexception (3), foreach (3), 100 (3), float (3), archivo (3), objeto (3), variables (3), simplexml (3), mail (3), while (3), print (3), ver (3), tools (3), todos (2), italiano (2), português (2), español (2), français (2), русский (2), deutsch (2), english (2), beautifier (2), diff (2), password (2), herramientas (2), python (2), java (2), git (2), libros (2), fragmentos (2), fluye (2), buenas (2), prácticas (2), múltiples (2), leer (2), información (2), page (2), sistema (2), ejecuta (2), personalizada (2), sentencia (2), condiciones (2), excepcionales (2), programa (2), verdadero (2), sobre (2), camino (2), sigue (2), global (2), set_exception_handler (2), integradas (2), específicos (2), punto (2), valor (2), deja (2), solo (2), tipo (2), todo (2), siempre (2), mensaje (2), parent (2), message (2), puedes (2), bloques (2), primero (2), final (2), negative (2), abc (2), number (2), value (2), parseage (2), int (2), is_numeric (2), varios (2), manera (2), getprevious (2), gettraceasstring (2), getline (2), getfile (2), cada (2), útiles (2), son (2), done (2), caught (2), division (2), zero (2), allowed (2), invalidargumentexception (2), del (2), lógica (2), escribir (2), parser (2), regex (2), math (2), fecha (2), yield (2), switch (2), stat (2), rewind (2), md5 (2), list (2), key (2), isset (2), include (2), for (2), file (2), empty (2), elseif (2), else (2), current (2), count (2), continue (2), connect (2), break (2), insert (2), constantes (2), oop (2), funciones (2), filtros (2), form (2), url (2), formularios (2), hash (2), 2026, derechos, reservados, hecho, desarrolladores, idioma, política, privacidad, contacto, acerca, empresa, tutoriales, ejemplos, gratuitos, web, desde, 2014, previous, yes, was, helpful, comprobar, lanzado, procesarla, comenzar, usan, graph, thrown, diagrama, continuación, muestra, ejecución, través, estructura, resérvelas, genuinamente, uses, tragarlas, capturadas, silencies, categorización, máquinas, escribe, mensajes, informativos, subclases, superan, básica, exacto, vuelve, inválido, realmente, responder, pronto, tarde, recuperarte, propaguen, hasta, central, risky, ordinarias, nivel, motor, argumento, incorrecto, atrapa, seguro, pero, úsalo, último, recurso, tragarte, accidentalmente, deberías, corregir, sobreescribes, llama, configuren, correctamente, geterrors, validationexception, ejemplo, menudo, subclase, vacía, suficiente, añade, necesites, comportamiento, adicional, allá, definir, propios, extendiendo, integrada, específica, dedicada, hace, sean, expresivos, reaccionar, específicamente, permite, adjuntar, adicionales, runtimeexception, orden, importa, dado, forman, jerarquía, coloca, amplios, contrario, amplio, capturará, antes, específico, tenga, oportunidad, get_class, único, tener, comprueban, arriba, hacia, abajo, cuyo, coincide, lanzada, gana, dos, relacionados, deben, manejarse, misma, combínalos, operador, pipe, duplicar, custom, void, envuelve, otra, pila, llamadas, útil, registro, número, línea, fue, creada, creó, entero, pasaste, humanos, devuelve, método, lleva, detalles, comunes, heredados, observa, segundo, nunca, imprime, porque, lanzamiento, aborta, inmediato, ejecutándose, throws, the, line, never, runs, envuelves, arriesgado, dentro, ejecutar, resto, salta, primer, coincidente, opcional, después, lanzó, convierte, adecuado, liberar, recursos, cerrar, bloqueo, versiones, posteriores, implementan, interfaz, cualquier, cosa, pueda, lanzarse, something, went, wrong, función, continuar, significativa, entrada, usuario, válida, conexión, fallida, faltante, fuera, rango, permitido, mantienen, separada, feliz, sea, esta, página, explica, ofrece, propias, representa, condición, inesperada, interrumpe, dejar, problema, rompa, script, silenciosamente, algo, sale, mal, luego, algún, sepa, recuperarse, registrarla, reportarla, capturas, lanzas, aprende, multi, zonas, horarias, zip, stream, network, mysqli, misc, libxml, palabras, clave, ftp, filter, directorios, calendario, zip_read, zip_open, zip_entry_read, zip_entry_open, zip_entry_name, zip_entry_filesize, zip_entry_compressionmethod, zip_entry_compressedsize, zip_entry_close, zip_close, from, xpath, xor, xml_set_unparsed_entity_decl_handler, xml_set_start_namespace_decl_handler, xml_set_processing_instruction_handler, xml_set_object, xml_set_notation_decl_handler, xml_set_external_entity_ref_handler, xml_set_end_namespace, decl, handler, xml_set_element_handler, xml_set_default_handler, xml_set_character_data_handler, xml_parser_set_option, xml_parser_get_option, xml_parser_free, xml_parser_create_ns, xml_parser_create, xml_parse_into_struct, xml_parse, xml_get_error_code, xml_get_current_line_number, xml_get_current_column_number, xml_get_current_byte_index, xml_error_string, wordwrap, warning_count, vsprintf, vprintf, vfprintf, var_export, var_dump, var, valid, utf8_encode, utf8_decode, usort, usleep, use_result, use, unset, unserialize, unpack, unlink, unixtojd, uniqid, umask, uksort, ucwords, ucfirst, uasort, trim, trigger_error, trait, touch, __tostring, tmpfile, timezone_version_get, timezone_transitions_get, timezone_open, timezone_offset_get, timezone_name_get, timezone_name_from_abbr, timezone_location_get, timezone_identifiers_list, timezone_abbreviations_list, time_sleep_until, time_nanosleep, time, thread_safe, thread_id, tempnam, tanh, tan, syslog, sys_getloadavg, symlink, substr_replace, substr_count, substr_compare, substr, strval, strtr, strtoupper, strtotime, strtolower, strtok, strstr, strspn, strrpos, strripos, strrev, strrchr, strptime, strpos, strpbrk, strncmp, strncasecmp, strnatcmp, strnatcasecmp, strlen, stristr, stripslashes, stripos, stripcslashes, strip_tags, strftime, strcspn, strcoll, strcmp, strchr, strcasecmp, str_word_count, str_split, str_shuffle, str_rot13, str_replace, str_repeat, str_pad, str_ireplace, str_getcsv, stmt_init, static, ssl_set, sscanf, srand, sqrt, sqlstate, sprintf, soundex, sort, socket_set_timeout, socket_set_blocking, socket_get_status, sleep, sizeof, sinh, sin, simplexml_load_string, simplexml_load_file, simplexml_import_dom, similar_text, shuffle, show_source, sha1_file, sha1, settype, setrawcookie, setlocale, setcookie, set_local_infile_handler, set_file_buffer, set_error_handler, set_charset, serialize, select_db, scandir, savexml, rtrim, rsort, round, rollback, rmdir, rewinddir, restore_exception_handler, restore_error_handler, reset, require_once, require, rename, registerxpathnamespace, refresh, reap_async_query, realpath_cache_size, realpath_cache_get, realpath, real_query, real_escape_string, real_connect, readlink, readfile, readdir, range, rand, rad2deg, quotemeta, quoted_printable_encode, quoted_printable_decode, query, protected, printf, print_r, prev, prepare, preg_split, preg_replace_callback_array, preg_replace_callback, preg_replace, preg_quote, preg_match_all, preg_match, preg_last_error, preg_grep, preg_filter, pow, pos, popen, mysqli_poll, ping, php_strip_whitespace, resumen, pfsockopen, pclose, pathinfo, parse_str, parse_ini_string, parse_ini_file, pack, output_reset_rewrite_vars, output_add_rewrite_var, ord, mysqli_options, openlog, opendir, octdec, ob_start, ob_list_handlers, ob_implicit_flush, ob_gzhandler, ob_get_level, ob_get_length, ob_get_flush, ob_get_contents, ob_get_clean, ob_flush, ob_end_flush, ob_end_clean, ob_clean, number_format, nl2br, nl_langinfo, next_result, natsort, natcasesort, namespace, multi_query, mt_srand, mt_rand, mt_getrandmax, move_uploaded_file, more_results, money_format, mktime, mkdir, min, microtime, metaphone, md5_file, max, ltrim, lstat, long2ip, log1p, log10, log, localtime, localeconv, linkinfo, link, libxml_use_internal_errors, libxml_set_streams_context, libxml_set_external_entity_loader, libxml_get_last_error, libxml_get_errors, libxml_disable_entity_loader, libxml_clear_errors, levenshtein, lchown, lchgrp, lcg_value, lcfirst, ksort, krsort, kill, juliantojd, json_encode, join, jewishtojd, jdtounix, jdtojulian, jdtojewish, jdtogregorian, jdtofrench, jdmonthname, jddayofweek, is_writeable, is_writable, is_uploaded_file, is_string, is_scalar, is_resource, is_real, is_readable, is_object, is_null, is_nan, is_long, is_link, is_iterable, is_integer, is_int, is_infinite, is_float, is_finite, is_file, is_executable, is_double, is_dir, is_countable, is_callable, is_bool, is_array, ip2long, intval, interface, intdiv, insteadof, instanceof, insert_id, init, info, inet_pton, inet_ntop, include_once, in_array, implode, implements, ignore_user_abort, idate, hypot, http_response_code, htmlspecialchars_decode, htmlspecialchars, htmlentities, html_entity_decode, hrtime, highlight_string, highlight_file, hexdec, hex2bin, hebrevc, hebrev, headers_sent, headers_list, header_remove, header_register_callback, header, haschildren, __halt_compiler, gregoriantojd, gmstrftime, gmmktime, gmdate, glob, gettype, gettrace, gettimeofday, getservbyport, getservbyname, getrandmax, getprotobynumber, getprotobyname, getnamespaces, getname, getmxrr, gethostname, gethostbynamel, gethostbyname, gethostbyaddr, getdocnamespaces, getdate, getcwd, getchildren, get_server_version, get_server_info, get_resource_type, get_proto_info, get_html_translation_table, get_host_info, get_defined_vars, get_connection_stats, get_client_version, get_client_stats, get_client_info, get_charset, get_browser, fwrite, ftruncate, ftp_systype, ftp_ssl_connect, ftp_size, ftp_site, ftp_set_option, ftp_rmdir, ftp_rename, ftp_rawlist, ftp_raw, ftp_quit, ftp_pwd, ftp_put, ftp_pasv, ftp_nlist, ftp_nb_put, ftp_nb_get, ftp_nb_fput, ftp_nb_fget, ftp_nb_continue, ftp_mlsd, ftp_mkdir, ftp_mdtm, ftp_login, ftp_get_option, ftp_get, ftp_fput, ftp_fget, ftp_exec, ftp_delete, ftp_connect, ftp_close, ftp_chmod, ftp_chdir, ftp_cdup, ftp_alloc, ftell, fstat, fsockopen, fseek, fscanf, frenchtojd, fread, fputs, fputcsv, fprintf, fprint, fpassthru, fopen, fnmatch, fmod, flush, floor, flock, floatval, filter_var_array, filter_var, filter_list, filter_input_array, filter_input, filter_id, filter_has_var, filetype, filesize, fileperms, fileowner, filemtime, fileinode, filegroup, filectime, fileatime, file_put_contents, file_get_contents, file_exists, field_seek, field_count, fgetss, fgets, fgetcsv, fgetc, fflush, fetch_row, fetch_object, fetch_lengths, fetch_fields, fetch_field_direct, fetch_field, fetch_assoc, fetch_array, fetch_all, feof, fclose, ezmlm_hash, extract, expm1, explode, exp, exit, eval, error_reporting, error_list, error_get_last, errno, endswitch, endif, endforeach, endfor, enddeclare, end, easter_days, easter_date, each, mysqli_dump_debug_info, doubleval, dns_get_record, dns_get_mx, dns_check_record, diskfreespace, disk_total_space, disk_free_space, dirname, dir, die, delete, deg2rad, defined, define, default, decoct, declare, dechex, decbin, debug_zval_dump, debug_print_backtrace, debug_backtrace, debug, date_timezone_set, date_timezone_get, date_timestamp_set, date_timestamp_get, date_time_set, date_sunset, date_sunrise, date_sun_info, date_sub, date_parse_from_format, date_parse, date_offset_get, date_modify, date_isodate_set, date_interval_format, date_interval_create_from_date_string, date_get_last_errors, date_format, date_diff, date_default_timezone_set, date_default_timezone_get, date_date_set, date_create_from_format, date_create, date_add, date, data_seek, crypt, crc32, count_chars, cosh, cos, copy, convert_uuencode, convert_uudecode, convert_cyr_string, constant, const, connection_timeout, connection_status, connection_aborted, connect_error, connect_errno, compact, commit, closelog, closedir, close, clone, clearstatcache, chunk_split, chroot, chr, chown, chop, chmod, children, chgrp, checkdnsrr, checkdate, chdir, character_set_name, change_user, ceil, case, callable, cal_to_jd, cal_info, cal_from_jd, cal_days_in_month, boolval, bindec, bin2hex, basename, base_convert, autocommit, attributes, atanh, atan2, atan, asxml, asort, asinh, asin, arsort, array_walk_recursive, array_walk, array_values, array_unshift, array_unique, array_uintersect_uassoc, array_uintersect_assoc, array_uintersect, array_udiff_uassoc, array_udiff_assoc, array_udiff, array_sum, array_splice, array_slice, array_shift, array_search, array_reverse, array_replace_recursive, array_replace, array_reduce, array_rand, array_push, array_product, array_pop, array_pad, array_multisort, array_merge_recursive, array_merge, array_map, array_keys, array_key_exists, array_intersect_ukey, array_intersect_uassoc, array_intersect_key, array_intersect_assoc, array_intersect, array_flip, array_filter, array_fill_keys, array_fill, array_diff_ukey, array_diff_uassoc, array_diff_key, array_diff_assoc, array_diff, array_count_values, array_combine, array_column, array_chunk, array_change_key_case, and, affected_rows, addslashes, addcslashes, addchild, addattribute, acosh, acos, abstract, abs, reference, encuesta, búsqueda, vivo, intro, dom, expat, cargar, analizadores, limit, update, eliminar, order, where, select, prepared, multiple, get, last, create, table, database, iterables, namespaces, propiedades, estáticas, estáticos, traits, interfaces, abstractas, herencia, modificadores, acceso, destructor, objetos, callback, avanzados, sesiones, cookies, subida, open, read, hora, json_decode, advanced, formulario, completo, required, validación, forms, superglobales, bucles, operadores, números, strings, comentarios, sintaxis, instalación, introducción, ámbito, ordenación, _server, _request, _post, multidimensionales, indexados, globals, _get, asociativos, tutorial, iniciar, sesión, buscar, formatters, reverse, sha256, length, calculator, colors, hsl, hex, mixer, converter, picker, general, cursos,
Text of the page (random words):
get date_default_timezone_set date_diff date_format date_get_last_errors date_interval_create_from_date_string date_interval_format date_isodate_set date_modify date_offset_get date_parse date_parse_from_format date_sub date_sun_info date_sunrise date_sunset date_time_set date_timestamp_get date_timestamp_set date_timezone_get date_timezone_set debug debug_backtrace debug_print_backtrace debug_zval_dump decbin dechex declare decoct default define defined deg2rad delete die dir dirname disk_free_space disk_total_space diskfreespace dns_check_record dns_get_mx dns_get_record do doubleval mysqli_dump_debug_info each easter_date easter_days echo echo else elseif empty empty end enddeclare endfor endforeach endif endswitch errno error error_get_last error_list error_log error_reporting eval exception exit exp explode expm1 extends extract ezmlm_hash fclose feof fetch_all fetch_array fetch_assoc fetch_field fetch_field_direct fetch_fields fetch_lengths fetch_object fetch_row fflush fgetc fgetcsv fgets fgetss field_count field_seek file file_exists file_get_contents file_put_contents fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype filter_has_var filter_id filter_input filter_input_array filter_list filter_var filter_var_array final finally floatval flock floor flush fmod fn fnmatch fopen for foreach fpassthru fprint fprintf fputcsv fputs fread frenchtojd fscanf fseek fsockopen fstat ftell ftp_alloc ftp_cdup ftp_chdir ftp_chmod ftp_close ftp_connect ftp_delete ftp_exec ftp_fget ftp_fput ftp_get ftp_get_option ftp_login ftp_mdtm ftp_mkdir ftp_mlsd ftp_nb_continue ftp_nb_fget ftp_nb_fput ftp_nb_get ftp_nb_put ftp_nlist ftp_pasv ftp_put ftp_pwd ftp_quit ftp_raw ftp_rawlist ftp_rename ftp_rmdir ftp_set_option ftp_site ftp_size ftp_ssl_connect ftp_systype ftruncate function fwrite get_browser get_charset get_client_info get_client_stats get_client_version get_connection_stats get_defined_vars get_host_info get_html_translation_table get_proto_info get_resource_type get_server_info get_server_version getchildren getcode getcwd getdate getdocnamespaces getfile gethostbyaddr gethostbyname gethostbynamel gethostname getline getmessage getmxrr getname getnamespaces getprevious getprotobyname getprotobynumber getrandmax getservbyname getservbyport gettimeofday gettrace gettraceasstring gettype glob global gmdate gmmktime gmstrftime gregoriantojd __halt_compiler haschildren header header_register_callback header_remove headers_list headers_sent hebrev hebrevc hex2bin hexdec highlight_file highlight_string hrtime html_entity_decode htmlentities htmlspecialchars htmlspecialchars_decode http_response_code hypot idate if ignore_user_abort implements implode in_array include include_once inet_ntop inet_pton info init insert_id instanceof insteadof intdiv interface intval ip2long is_array is_bool is_callable is_countable is_dir is_double is_executable is_file is_finite is_float is_infinite is_int is_integer is_iterable is_link is_long is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_string is_uploaded_file is_writable is_writeable isset isset jddayofweek jdmonthname jdtofrench jdtogregorian jdtojewish jdtojulian jdtounix jewishtojd join json_encode juliantojd key key kill krsort ksort lcfirst lcg_value lchgrp lchown levenshtein libxml_clear_errors libxml_disable_entity_loader libxml_get_errors libxml_get_last_error libxml_set_external_entity_loader libxml_set_streams_context libxml_use_internal_errors link linkinfo list list localeconv localtime log log10 log1p long2ip lstat ltrim mail max md5 md5_file metaphone microtime min mkdir mktime money_format more_results move_uploaded_file mt_getrandmax mt_rand mt_srand multi_query namespace natcasesort natsort new next next next_result nl_langinfo nl2br number_format ob_clean ob_end_clean ob_end_flush ob_flush ob_get_clean ob_get_contents ob_get_flush ob_get_length ob_get_level ob_gzhandler ob_implicit_flush ob_list_handlers ob_start octdec opendir openlog mysqli_options or ord output_add_rewrite_var output_reset_rewrite_vars pack parse_ini_file parse_ini_string parse_str pathinfo pclose pfsockopen resumen de php php_strip_whitespace pi ping mysqli_poll popen pos pow preg_filter preg_grep preg_last_error preg_match preg_match_all preg_quote preg_replace preg_replace_callback preg_replace_callback_array preg_split prepare prev print print print_r printf private protected public query quoted_printable_decode quoted_printable_encode quotemeta rad2deg rand range readdir readfile readlink real_connect real_escape_string real_query realpath realpath_cache_get realpath_cache_size reap_async_query refresh registerxpathnamespace rename require require_once reset restore_error_handler restore_exception_handler return rewind rewind rewinddir rmdir rollback round rsort rtrim savexml scandir select_db serialize set_charset set_error_handler set_exception_handler set_file_buffer set_local_infile_handler setcookie setlocale setrawcookie settype sha1 sha1_file show_source shuffle similar_text simplexml_import_dom simplexml_load_file simplexml_load_string sin sinh sizeof sleep socket_get_status socket_set_blocking socket_set_timeout sort soundex sprintf sqlstate sqrt srand sscanf ssl_set stat stat static stmt_init str_getcsv str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split str_word_count strcasecmp strchr strcmp strcoll strcspn strftime strip_tags stripcslashes stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk strpos strptime strrchr strrev strripos strrpos strspn strstr strtok strtolower strtotime strtoupper strtr strval substr substr_compare substr_count substr_replace switch symlink sys_getloadavg syslog tan tanh tempnam thread_id thread_safe throw time time_nanosleep time_sleep_until timezone_abbreviations_list timezone_identifiers_list timezone_location_get timezone_name_from_abbr timezone_name_get timezone_offset_get timezone_open timezone_transitions_get timezone_version_get tmpfile __tostring touch trait trigger_error trim try uasort ucfirst ucwords uksort umask uniqid unixtojd unlink unpack unserialize unset use use_result usleep usort utf8_decode utf8_encode valid var var_dump var_export vfprintf vprintf vsprintf warning_count while wordwrap xml_error_string xml_get_current_byte_index xml_get_current_column_number xml_get_current_line_number xml_get_error_code xml_parse xml_parse_into_struct xml_parser_create xml_parser_create_ns xml_parser_free xml_parser_get_option xml_parser_set_option xml_set_character_data_handler xml_set_default_handler xml_set_element_handler xml_set_end_namespace decl handler xml_set_external_entity_ref_handler xml_set_notation_decl_handler xml_set_object xml_set_processing_instruction_handler xml_set_start_namespace_decl_handler xml_set_unparsed_entity_decl_handler xor xpath yield yield from zip_close zip_entry_close zip_entry_compressedsize zip_entry_compressionmethod zip_entry_filesize zip_entry_name zip_entry_open zip_entry_read zip_open zip_read php array calendario php fecha en php directorios en php errores en php php exception sistema de archivos php php filter php ftp php json palabras clave de php php libxml php mail php math php misc php mysqli php network control de salida php php regex php simplexml php stream php string manejo de variables en php php xml parser php zip zonas horarias en php php exception aprende las excepciones php cómo lanzar y capturar errores con try catch finally métodos de la clase exception multi catch y clases de excepción personalizadas qué es una excepción una excepción es un objeto que representa un error o una condición inesperada que interrumpe el flujo normal de un programa en lugar de dejar que un problema rompa el script silenciosamente lanzas una excepción en el punto donde algo sale mal y luego la capturas en algún lugar que sepa cómo recuperarse registrarla o reportarla esta página explica cómo lanzar y capturar excepciones con try catch finally los métodos que te ofrece cada objeto de excepción cómo capturar varios tipos de excepciones y cómo escribir tus propias clases de excepción las excepciones son útiles cuando una función no puede continuar de manera significativa entrada de usuario no válida una conexión a la base de datos fallida un archivo faltante o un valor fuera del rango permitido mantienen la lógica de manejo de errores separada de la lógica normal para que el camino feliz sea más legible throw new exception something went wrong copiar en php 7 y versiones posteriores tanto exception como error implementan la interfaz throwable por lo que cualquier cosa que pueda lanzarse es un throwable lanzar y capturar con try catch finally envuelves el código arriesgado en un bloque try si una sentencia dentro lanza una excepción php deja de ejecutar el resto del bloque try y salta al primer catch coincidente el bloque finally opcional siempre se ejecuta después tanto si se lanzó una excepción como si no lo que lo convierte en el lugar adecuado para liberar recursos cerrar un archivo un manejador de base de datos un bloqueo php function divide a b if b 0 throw new invalidargumentexception division by zero is not allowed return a b try echo divide 10 2 n 5 echo divide 10 0 n throws the next line never runs catch invalidargumentexception e echo caught e getmessage n finally echo done n copiar salida 5 caught division by zero is not allowed done copiar observa que el segundo echo divide nunca se imprime porque el lanzamiento aborta el bloque try de inmediato el bloque finally sigue ejecutándose leer información de una excepción cada objeto de excepción lleva detalles útiles los métodos más comunes todos heredados de la clase base exception son método devuelve getmessage el mensaje de error legible por humanos getcode el código de error entero que pasaste al constructor getfile el archivo donde se creó la excepción getline el número de línea donde fue creada gettraceasstring la pila de llamadas como string útil para registro getprevious la excepción anterior cuando una envuelve a otra php class insufficientfundsexception extends exception class account private float balance public function __construct float balance this balance balance public function withdraw float amount void if amount this balance throw new insufficientfundsexception cannot withdraw amount balance is this balance 100 a custom error code this balance amount account new account 50 try account withdraw 80 catch insufficientfundsexception e echo e getmessage n cannot withdraw 80 balance is 50 echo code e getcode n code 100 copiar salida cannot withdraw 80 balance is 50 code 100 copiar capturar múltiples tipos de excepciones un único try puede tener varios bloques catch que se comprueban de arriba hacia abajo el primero cuyo tipo coincide con la excepción lanzada gana si dos tipos de excepción no relacionados deben manejarse de la misma manera combínalos en un bloque con el operador pipe en lugar de duplicar código php function parseage string input int if is_numeric input throw new typeerror input is not a number age int input if age 0 throw new rangeexception age cannot be negative return age foreach 42 abc 5 as value try echo parseage value n catch typeerror rangeexception e echo get_class e e getmessage n copiar salida 42 typeerror abc is not a number rangeexception age cannot be negative copiar el orden importa dado que las excepciones php forman una jerarquía coloca los tipos más específicos primero y los más amplios como exception o throwable al final de lo contrario el bloque amplio lo capturará todo antes de que el específico tenga oportunidad crear excepciones personalizadas más allá de las clases integradas puedes definir tus propios tipos de excepción extendiendo exception o una integrada más específica como runtimeexception una clase dedicada hace que tus bloques catch sean expresivos puedes reaccionar a tu error específicamente y te permite adjuntar datos adicionales en el ejemplo de account anterior insufficientfundsexception es una excepción personalizada a menudo una subclase vacía es suficiente añade métodos solo cuando necesites comportamiento adicional php class validationexception extends exception private array errors public function __construct string message array errors parent __construct message this errors errors public function geterrors array return this errors copiar si sobreescribes el constructor llama siempre a parent __construct para que el mensaje el código y la excepción anterior se configuren correctamente capturar throwable para manejar tanto excepciones ordinarias como errores a nivel de motor como un typeerror por un tipo de argumento incorrecto captura throwable es el atrapa todo más seguro pero úsalo como último recurso para no tragarte accidentalmente errores que deberías corregir try risky code catch throwable e error_log e getmessage copiar buenas prácticas captura solo lo que puedas manejar deja que las excepciones de las que no puedas recuperarte se propaguen hasta un manejador central lanza pronto captura tarde lanza en el punto exacto donde un valor se vuelve inválido captura donde realmente puedas responder usa tipos específicos las subclases personalizadas o integradas superan a una exception básica para el flujo de control escribe mensajes informativos y usa getcode para la categorización legible por máquinas registra no silencies registra las excepciones con error_log en lugar de tragarlas para las excepciones no capturadas registra un manejador global con set_exception_handler no uses excepciones para el flujo normal resérvelas para condiciones genuinamente excepcionales cómo fluye el control el diagrama a continuación muestra el camino que sigue la ejecución a través de una estructura try catch finally graph td try try block no exception finally finally block try exception thrown catch catch block catch finally práctica práctica qué es verdadero sobre el manejo de excepciones en php qué es verdadero sobre el manejo de excepciones en php las excepciones se usan para manejar errores y condiciones excepcionales en el flujo de un programa no se puede comenzar una sentencia php con try en php el bloque catch se usa para capturar la excepción y procesarla en php no se puede crear una clase de excepción personalizada el bloque finally se ejecuta tanto si se ha lanzado una excepción como si no comprobar was this page helpful yes no previous errores en php next sistema de archivos php on this page qué es una excepción lanzar y capturar con try catch finally leer información de una excepción capturar múltiples tipos de excepciones crear excepciones personalizadas buenas prácticas cómo fluye el control práctica w3docs tutoriales ejemplos ejercicios fragmentos y cuestionarios gratuitos para la web desde 2014 libros aprender html aprender css aprender javascript aprender git aprender java aprender php aprender python práctica ejercicios cuestionarios editor try it herramientas html editor...
|